简体   繁体   中英

Python recursive function definition storage issue

I am trying to get a list of functions defined recursively by storing each step of a math serie: x^0+x^1+x^2+x^3+...f0(x)=1, f1(x)=1+x, f2(x)=1+x+x², f3(x)=1+x+x²+x³, ...

I coded this in python:

n = 3
devs = [lambda x: 1]
for k in range(n):
    devs.append(lambda x, f=devs[k]: f(x) + x**(k+1))
print(devs[-1](4))  # x=4

I learned in this answer that you need to pass the previous function as default argument in order to solve the maximum recursion depth error, but this outputs 193 .
I think it has to do with the k in the default parameter. It seems to calculate: 1+4^3+4^3+4^3=193 , or more accurately 1+n*x^n instead of x^0+x^1+...+x^n

Can you please tell me what am I doing wrong here?

I think the same question you linked has the answer to your problem. Because the k inside the function is evaluated only outside the loop, it will have the last value from the loop. You can check the documention for how it works in depth. The correct code is

n = 4
devs = [lambda x: 1]
for k in range(n):
    devs.append(lambda x, f=devs[k], j=k: f(x) + x**(j+1))

One liner just for fun!

n=10
devs = (lambda f:[f] + [f := (lambda x, a=k, g=f: g(x) + x**(a+1)) for k in range(n)])(lambda x:1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM