我试图用字典表示多项式,将幂作为键,元素作为系数。我一直试图重载__sub __
函数,但由于我在苦苦挣扎,我想我应该重载__neg __
函数并稍后将其应用于__sub __
。当我使用Python列表时,我很容易做到,但我不知道如何使用字典。所以我只是将每个元素(系数乘以-1)乘以而不是密钥(指数)。之后,如何调用__neg __
函数中的__sub __
函数?
class Polynomial(object):
def __init__(self, coefficients):
self.coefficients = coefficients
def __str__(self):
polytostring = ' '
for exponent, coefficient in self.coefficients.iteritems():
if exponent == 0:
polytostring += '%s + ' % coefficient
else:
polytostring += '%sx^%s + ' % (coefficient, exponent)
polytostring = polytostring.strip(" + ")
return polytostring
def __add__(self, other):
if isinstance(other, Polynomial):
if max(other.coefficients) > max(self.coefficients):
coefficients = other.coefficients
add_poly = self
else:
coefficients = self.coefficients
add_poly = other
for exponent, coefficient in add_poly.coefficients.iteritems():
if exponent in coefficients:
coefficients[exponent] += add_poly.coefficients[exponent]
else:
coefficients[exponent] = coefficient
else:
coefficients = self.coefficients
sum = Polynomial(coefficients)
return sum
def __neg__(self):
pass
def __sub__(self,other):
pass
dict1 = {0:1, 1:-1}
p1 = Polynomial(dict1)
dict2 = {1:1, 4:-6, 5:-1, 3:2}
p2 = Polynomial(dict2)
print p1
print p2
p3 = p1+p2
print "The sum is:", p3.coefficients
print "The sum in string rep is:", p3
print p1-p2
答案 0 :(得分:0)
只有一元减号会调用 neg ,例如:
def __sub__(self, other):
return self + -other
<强>更新强>
如果没有看到明确的错误消息和代码,那么很难理解你的错误,但是创建一个简单的Poly类作为dict的子类:
class Poly(dict):
def __init__(self, *args, **kwargs):
super(Poly, self).__init__(*args, **kwargs)
def __str__(self):
return "".join(("{:+}x^{}" if e else "{}").format(c, e)
for e, c in sorted(self.items()) if c)
def __add__(self, other):
return Poly({k: self.get(k, 0) + other.get(k, 0) for k in set(self) | set(other)})
def __neg__(self):
return Poly({k: -v for k, v in self.items()})
def __sub__(self, other):
return self + -other
>>> x = Poly({0:1, 1:-1})
>>> y = Poly({1:1, 4:-6, 5:-1, 3:2})
>>> print(x+y)
1+2x^3-6x^4-1x^5
>>> print(x-y)
1-2x^1-2x^3+6x^4+1x^5
虽然直接添加 sub 真的不难:
def __sub__(self, other):
return Poly({k: self.get(k, 0) - other.get(k, 0) for k in set(self) | set(other)})