刚开始,如果这是个愚蠢的问题,我向你道歉。Python2.7如果重要的话。我在写一个程序来计算一个多项式,它的系数是由某个x上元组的元素表示的,这个元组的幂是系数的指数。当所有的系数都不同的时候,它运行得很好,我遇到的问题是,任何一个系数都是相同的。代码如下-def evaluate_poly(poly, x):
"""polynomial coefficients represented by elements of tuple.
each coefficient evaluated at x ** index of coefficient"""
poly_sum = 0.0
for coefficient in poly:
val = coefficient * (x ** poly.index(coefficient))
poly_sum += val
return poly_sum
poly = (1, 2, 3)
x = 5
print evaluate_poly(poly, x)
##for coefficient in poly:
##print poly.index(coefficient)
它会像您预期的那样返回86。在
注释输出print语句将返回poly中每个元素的索引。当它们都是不同的(1,2,3)时,它会返回你期望的值(0,1,2),但是如果任何元素是相同的(1,1,2),它们的指数也将相同(0,0,1),所以我只能计算所有系数都不同的多项式。我做错什么了?我想这跟-
^{pr2}$
但我不知道为什么。提前谢谢