【问题标题】:Repeated Function Application重复功能应用
【发布时间】:2011-05-26 22:54:53
【问题描述】:

我遇到以下问题:编写递归函数重复应用,将函数作为参数 一个参数的 f 和一个正整数 n。重复应用的结果是一个参数的函数,该函数将 f 应用于该参数 n 次。

所以,例如,我们会有

重复应用(λ x:x+1,10)(100)==> 110

您可以假设已经定义了以下函数。您不必使用它,但它可以为一个漂亮的解决方案做出贡献。

定义组成(f,g): 返回 lambda x: f(g(x))

到目前为止,我已经写了这个

def compose(f,g):
    return lambda x: f(g(x))

def recApply(f,n):
    for i in range(n):
        return recApply(compose(f,f), n-1)
    return f

我在某个地方出错了,因为使用上面的示例 recApply(lambda x: x+1,10)(100) 我得到 1124。

帮助非常感谢

【问题讨论】:

  • 您最终添加了 1024 而不是 10。想想你为什么拥有2 的力量。

标签: python recursion lambda


【解决方案1】:

正确答案是:

def recApply(func, n):
    if n > 1:
        rec_func = recApply(func, n - 1)
        return lambda x: func(rec_func(x))
    return func

还有输出:

>>>> print recApply(lambda x: x+1,10)(100)
110

【讨论】:

    【解决方案2】:

    我有一个基于 lambdas 的解决方案:

    >>> f = lambda x: x + 10
    >>> iterate = lambda f, n, x : reduce(lambda x, y: f(x), range(n), x)
    >>> iterate(f, 10, 3)
    103
    >>> iterate(f, 4, 4)
    44
    >>> f10 = lambda x: iterate(f, 10, x)
    >>> f10(5)
    105
    

    【讨论】:

      【解决方案3】:

      您的功能需要一些工作:

      • 您的for 循环中有一个return,因此您立即返回而不是运行循环。
      • 您在for 循环中有一个递归调用,因此您进行了太多的迭代。任选其一。
      • 在将函数组合堆叠在一起时要小心,因为您是在进行幂组合而不是线性组合。

      你能告诉我们你到底想做什么吗?

      编辑:因为其他人都在发布答案:

      recApply = lambda f, n: lambda x: x if n == 0 else recApply(f, n-1)(f(x))
      

      【讨论】:

      • 看来代码应该是:recApply = lambda f, n: lambda x: x if n == 0 else recApply(f, n-1)(f(x)),否则返回价值永远不变
      【解决方案4】:

      我认为这是某种练习。有几种方法可以做到,这里有一个简短的:

      >>> repeatedlyApply = lambda f, n: reduce(lambda f1, f2: compose(f1, f2), [f]*n)
      >>> repeatedlyApply(lambda x: x+1,10)(100)
      110
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        • 2019-09-27
        相关资源
        最近更新 更多