简体   繁体   English

Python 递归 function 定义存储问题

[英]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³, ...我试图通过存储数学系列的每个步骤来获取递归定义的函数列表: 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:我在 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 .我在这个答案中了解到,您需要将之前的 function 作为默认参数传递,以解决最大递归深度错误,但这会输出193
I think it has to do with the k in the default parameter.我认为这与默认参数中的k有关。 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它似乎计算: 1+4^3+4^3+4^3=193 ,或更准确地说是1+n*x^n而不是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.因为 function 中的 k 仅在循环外部进行评估,所以它将具有循环中的最后一个值。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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