我试图用字典来表示多项式,以包含作为键的幂和作为系数的元素。我一直在尝试重载该__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