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),所以我真的只能评估所有系数不同的多项式。我在这做错了什么?我觉得它与之有关 -
poly.index(coefficient)
但我无法弄明白为什么。提前致谢
答案 0 :(得分:1)
使用enumerate,index将获取第一个出现的索引,因此对于重复元素,它显然会失败,在使用poly.index(1)
的代码(1, 1, 2)
中每次都要返回0
:
使用枚举将为每个元素提供每个实际索引,并且更有效:
def evaluate_poly(poly, x):
"""polynomial coefficients represented by elements of tuple.
each coefficient evaluated at x ** index of coefficient"""
poly_sum = 0.0
# ind is each index, coefficient is each element
for ind, coefficient in enumerate(poly):
# no need for val just += coefficient * (x ** ind)
poly_sum += coefficient * (x ** ind)
return poly_sum
如果您print(list(enumerate(poly)))
,您会在列表中看到每个元素及其索引:
[(0, 1), (1, 1), (2, 3)]
因此,每次循环中ind
都会引用多边形列表中每个coefficient
的索引。
您也可以使用generator
返回sum表达式def evaluate_poly(poly, x):
"""polynomial coefficients represented by elements of tuple.
each coefficient evaluated at x ** index of coefficient"""
return sum((coefficient * (x ** ind) for ind, coefficient in enumerate(poly)),0.0)
使用0.0
作为 start 值将表示返回float而不是int。您也可以投射float(sum...
,但我认为将起始值作为浮点数传递更简单。
答案 1 :(得分:0)
在这里试试这个:
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 ind, coefficient in enumerate(poly):
print ind
val = coefficient * (x ** ind)
poly_sum += val
return poly_sum
poly = (1, 2, 3)
x = 5
print evaluate_poly(poly, x)
它也适用于poly = (1, 1, 3)
!