我写了一个小类,它以字典作为参数的初始化程序。以下字典{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 对象。
如果我在得到正确指数的那一刻将多项式自身相乘,但除了初始项和结束项之外,所有系数都相差甚远。