我写了一个小类,它的初始值设定项将字典作为参数。下面的字典{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 solution but easily understandable.
We check first if our exponent is present in both polynomials
then if its only present in one and the symmetric case, adding the result
to the dictionary add
"""
add = {}
for exponent in self.polynom:
if exponent in other.polynom:
add[exponent] = self.polynom[exponent] + other.polynom[exponent]
for exponent in self.polynom:
if exponent not in other.polynom:
add[exponent] = self.polynom[exponent]
for exponent in other.polynom:
if exponent not in self.polynom:
add[exponent] = other.polynom[exponent]
return add
def __mul__(self, other):
mult = {}
for exponent1 in self.polynom:
for exponent2 in other.polynom:
mult[exponent1 + exponent2] = self.coefficient(exponent1) * other.coefficient(exponent2)
return mult
关键的一步,也是我的主要问题是,在乘法的过程中,我想利用加法。但是我对OOP绝对是新手,我不知道如何初始化一个Polynom对象来执行加法运算。在
如果我把一个多项式乘以它本身,我得到了正确的指数,但是除了初始项和结束项,所有的系数都离得很远。在