重复功能应用

Ben*_*nji 5 python recursion lambda

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

所以,例如,我们会

repeatedlyApply(lambda x: x+1,10)(100) ==> 110

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

def compose(f,g):
    return 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
Run Code Online (Sandbox Code Playgroud)

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

非常感谢

ber*_*rni 5

正确答案是:

def recApply(func, n):
    if n > 1:
        rec_func = recApply(func, n - 1)
        return lambda x: func(rec_func(x))
    return func
Run Code Online (Sandbox Code Playgroud)

和输出:

>>>> print recApply(lambda x: x+1,10)(100)
110
Run Code Online (Sandbox Code Playgroud)


sve*_*rre 4

您的函数需要一些工作:

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

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

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

recApply = lambda f, n: lambda x: x if n == 0 else recApply(f, n-1)(f(x))
Run Code Online (Sandbox Code Playgroud)