1

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?

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.