-1

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

1 回答 1

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

虽然直接添加一个子并不难:

    def __sub__(self, other):
        return Poly({k: self.get(k, 0) - other.get(k, 0) for k in set(self) | set(other)})
于 2015-04-07T15:22:29.780 回答