Skip to main content
 首页 » 编程设计

Python:相同元组元素的索引也相同

2025年05月04日11bonelee

刚刚开始,如果这是一个愚蠢的问题,我深表歉意。 Python 2.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), 所以我真的只能评估所有系数都不同的多项式。我在这里做错了什么?我认为这与 -

poly.index(coefficient) 

但我不明白为什么。提前致谢

请您参考如下方法:

使用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 都指的是 poly 列表中每个 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... 但我认为将起始值作为 float 传递更简单。