def evalPoly(lst, x):
total = 0
for power, coeff in enumerate(lst): # starts at 0 by default
total += (x**power) * coeff
return total
或者,可以使用列表,然后使用sum:def evalPoly(lst, x):
total = []
for power, coeff in enumerate(lst):
total.append((x**power) * coeff)
return sum(total)
不枚举:def evalPoly(lst, x):
total, power = 0, 0
for coeff in lst:
total += (x**power) * coeff
power += 1
return total
非枚举方法的替代方法:def evalPoly(lst, x):
total = 0
for power in range(len(lst)):
total += (x**power) * lst[power] # lst[power] is the coefficient
return total
同样@DSM声明,您可以将其放在一行中:def evalPoly(lst, x):
return sum((x**power) * coeff for power, coeff in enumerate(lst))
或者,