0
我已經寫了一個小類,其初始化程序需要作爲參數的字典。以下字典{2:3, 4:5, 6:7}
轉換爲多項式3x^2 + 5x^4 + 7x^6
,因此我的字典的鍵是指數,它的值是係數。在Python中使用多項式乘以字典
我已經成功設法使用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對象,以便我可以執行加法運算。
如果我在獲得正確指數的那一刻乘上一個多項式本身,但除了初始項和結束項之外,所有的係數都是關閉的。
係數已關閉,因爲擴展中的多個術語對答案中的相同功能作出了貢獻,並且在此情況下您將在同一個指數鍵上重寫'mult'條目。 'exponent1,exponent2 = 1,3',然後是'exponent1,exponent2 = 2,2'時會發生什麼? – xnx 2014-12-05 21:30:34
我同意@xnx,但我不明白如何解決它,有沒有簡單的方法來防止這與if/else參數? – Spaced 2014-12-05 21:32:23
如果這是一個學習練習,那麼盡一切辦法去做。但是如果你想用這個來認真對待任何事情,我的建議不是重新發明輪子,而只是看看[sympy](http://docs.sympy.org/latest/tutorial/intro.html ),它處理多項式(除其他外)非常好。 – 2014-12-06 01:13:23