[英]How does enumerate work in polynomial function (Python)?
I am a Python beginner and a bit confused about enumerate function in summing the polynomial problem in the following SO thread: 我是Python初学者,对以下SO线程中多项式问题的求和有点困惑:
Evaluating Polynomial coefficients 评估多项式系数
The thread includes several ways to solve the summing of polynomials. 该线程包括几种解决多项式求和的方法。 I understand the following version well:
我很了解以下版本:
def evalP(lst, x):
total = 0
for power in range(len(lst)):
total += (x**power) * lst[power] # lst[power] is the coefficient
return total
Eg if I take third degree polynomial with x = 2, the program returns 15 as I expected based on pen and paper calculations: 例如,如果我采用x = 2的三次多项式,则程序将根据笔和纸的计算返回15,这是我期望的:
evalP([1,1,1,1],2)
Out[64]:
15
But there is another, neater version of doing this that uses enumerate function: 但是,还有另一个更简洁的版本使用枚举功能:
evalPoly = lambda lst, x: sum((x**power) * coeff for power, coeff in enumerate(lst))
The problem is that I just can't get that previous result replicated with that. 问题是我只是无法复制以前的结果。 This is what I've tried:
这是我尝试过的:
coeff = 1
power = 3
lst = (power,coeff)
x = 2
evalPoly(lst,x)
And this is what the program returns: 这是程序返回的内容:
Out[68]:
5
Not what I expected. 不是我所期望的。 I think I have misunderstood how that enumerate version takes on the coefficient.
我想我误解了该枚举版本如何承担系数。 Could anyone tell me how I am thinking this wrong?
谁能告诉我我是怎么想的呢?
The previous version seems more general as it allows for differing coefficients in the list, whereas I am not sure what that scalar in enumerate version represents. 前一个版本看起来更通用,因为它允许列表中使用不同的系数,而我不确定枚举版本中的标量表示什么。
You should call evalPoly
with the same arguments as evalP
, eg evalPoly([1,1,1,1],2)
你应该叫
evalPoly
具有相同的参数evalP
,如evalPoly([1,1,1,1],2)
When you call evalPoly([3,1],2)
, it return 3*2^0 + 1*2^1 which equals 5. 当您调用
evalPoly([3,1],2)
,它返回3 * 2 ^ 0 + 1 * 2 ^ 1等于5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.