使用lambda的递归函数,为什么这不起作用?

MTV*_*DNA 6 python recursion lambda

我有一个函数做一些计算,g(x).我现在想写一个计算g(g(g(... g(x))))的函数,其中g被应用n次.我尝试使用repeat_fn(见下文)这样做,但这不起作用.

根据使用lambda表达式递归函数,解决方案是使用functools.partial.这确实有效,但我不明白怎么做.另外,我不明白为什么我的方法不起作用.

g = lambda x: 2*x

# Function that returns the fˆn map
def repeat_fn(f, n):
     if n == 1:
         return f
    else:
        return lambda y: f( repeat_fn(f(y), n-1) )


 def repeat_fn_base(fn, n, x):
    if n == 1:
        return fn(x)
    else:
        return fn(repeat_fn_base(fn, n-1, x))

def repeat_fn2(fn, n):
    return functools.partial(repeat_fn_base, fn, n)


j = repeat_fn2(g, 5)
print(type(j))
print(j(2))

k = repeat_fn(g, 5)
print(type(k))
print(k(2))
Run Code Online (Sandbox Code Playgroud)

它似乎repeat_fn只在我使用时调用一次k = repeat_fn(g, 5),而我希望它被调用五次.显然,在我用参数提供k之前,递归才会开始.还会print(k(2))出现以下错误:TypeError: unsupported operand type(s) for *: 'int' and 'function'.

这令我感到惊讶,因为例如h = g(g(x)工作得很好.

任何人都可以对此有所了解吗?谢谢!

tob*_*s_k 5

使用return lambda y: f( repeat_fn(f(y), n-1) ),您调用repeat_fnf参数是结果f(y),即不是函数.相反,你应该只传递f然后将fn_repeat(函数)的结果应用于f(y)(反之亦然).

def repeat_fn(f, n):
    if n == 1:
         return f
    else:
        return lambda y: repeat_fn(f, n-1)(f(y))

k = repeat_fn(lambda x: 2*x, 5)
print(k(2))  # 64
Run Code Online (Sandbox Code Playgroud)