anyone knows why my program is not giving result?
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
Iterating over a dict
yields keys, not items.
for k, value in other.coeff.iteritems():
for k in d:
sum +=d[k]*x**k
return sum
change to
for k, v in d.iteritems():
sum +=v*x**k
return sum
EDIT: I see the problem...
in __add__()
, value is not defined therefore it gets set to None and no result will happen
精彩评论