我写了一个小类,它的初始值设定项将字典作为参数。下面的字典{2:3, 4:5, 6:7}翻译成多项式3x^2 + 5x^4 + 7x^6,所以我的字典的键是指数,它的值是系数。在
我已经成功地使用eq方法实现了类中两个多项式的比较,我可以添加它们。这是我的代码:class Polynomial(object):
def __init__(self, polynom = {}):
self.polynom = polynom
self.poly_string = self.nicePolynom(polynom) #just a method that will make my output look nice
def __str__(self):
return self.poly_string # for debugging purposes
def coefficient(self, exponent):
"""
A small function that returns the coefficient of the corresponding exponent
i.e. if our Polynomial is P = 3x^9 then p.coefficient(9) return 3
"""
try:
return self.polynom[exponent]
except KeyError:
pass
def __add__(self,other):
"""
Overloading the + operator
Not the most elegant s