有谁知道为什么我的程序没有给出结果?

时间:2010-11-07 08:42:36

标签: python class

import copy
class Polynomial(dict):
    def __init__(self, coefficients):
        self.coeff = coefficients

    def dictionary(self,x):
        sum=0.0
        d=self.coeff
        for k in d:
            sum +=d[k]*x**k
        return sum
    def __add__(self, other):
        new=copy.deepcopy(self)
        for k,d in other.coeff:
            if k in new:
               new[k] +=value
            else:
                  new[k]=value
        return Polynomial(new)

p = Polynomial({20:1,1:-1,100:4})
q = Polynomial({1:1,100:-3})

print q+q

2 个答案:

答案 0 :(得分:4)

迭代dict会产生密钥,而非项目。

for k, value in other.coeff.iteritems():

答案 1 :(得分:2)

    for k in d:
        sum +=d[k]*x**k
    return sum

更改为

    for k, v in d.iteritems():
        sum +=v*x**k
    return sum
编辑:我看到了问题......

__add__()中,未定义值,因此将其设置为None并且不会发生任何结果