Python 中的多项式,使用字典
Polynomials in Python, using dictionaries
我尝试用字典表示多项式,以包含作为键的幂和作为系数的元素。我一直在尝试重载 __sub __
函数,但由于我一直在努力,我想我应该只重载 __neg __
函数,然后将其应用于 __sub __
。当我为 Python 使用列表时,我很容易做到这一点,但我不知道如何使用字典来做到这一点。所以我只是将每个元素(系数乘以 -1)而不是键(指数)相乘。之后,如何在__sub __
函数中调用__neg __
函数?
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
只有一元减号会调用 neg,例如:
def __sub__(self, other):
return self + -other
更新
如果没有看到明确的错误消息和代码,那么很难理解你出了什么问题,但是创建一个简单的 Poly class 作为 dict:class 的 subclass:
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)})
我尝试用字典表示多项式,以包含作为键的幂和作为系数的元素。我一直在尝试重载 __sub __
函数,但由于我一直在努力,我想我应该只重载 __neg __
函数,然后将其应用于 __sub __
。当我为 Python 使用列表时,我很容易做到这一点,但我不知道如何使用字典来做到这一点。所以我只是将每个元素(系数乘以 -1)而不是键(指数)相乘。之后,如何在__sub __
函数中调用__neg __
函数?
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
只有一元减号会调用 neg,例如:
def __sub__(self, other):
return self + -other
更新
如果没有看到明确的错误消息和代码,那么很难理解你出了什么问题,但是创建一个简单的 Poly class 作为 dict:class 的 subclass:
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)})