我被要求編寫一個程序來計算n和m度的兩個多項式的相加。我做了兩個字典(一個用於第一個多項式,另一個用於另一個多項式),因爲每個字典都有作爲值和度數的係數作爲關鍵字,所以我可以檢查兩個字典中的關鍵字是否相同,然後我可以將他們值。但我不知道爲什麼我總是得到一個錯誤。到目前爲止我的代碼是:使用python求和兩個多項式的問題
class poly:
def __init__(self, L=[], D=[]):
self.coef=L
self.deg=D
def __add__(self,L2):
if len(self.coef)>len(self.deg):
dec=dict(zip(self.deg,self.coef))
dec[0]=self.coef[-1]
else:
dec=dict(zip(self.deg,self.coef))
Dec1=dec
if len(L2.coef)>len(L2.deg):
dec=dict(zip(L2.deg,L2.coef))
dec[0]=L2.coef[-1]
else:
dec=dict(zip(L2.deg,L2.coef))
Dec2=dec
p=[]
if len(Dec2)>len(Dec1):
for i in Dec2:
if i in Dec1:
s=Dec1[i]+Dec2[i]
p=p+[s]
else:
p=p+p[Dec2[i]]
for x in Dec1:
if x in Dec2:
p=p
else:
p=p+[dec1[x]]
return(poly(p))
if len(Dec2)<len(Dec1):
for x in Dec1:
if x in Dec2:
g=Dec1[x]
p=p+[g]
else:
p=p+[Dec1[x]]
for m in Dec2:
if m in Dec1:
p=p
else:
p=p+[Dec2[m]]
return (poly(p))
此代碼不爲我所有的例子,如
>>> p=poly([2,4,7,34],[6,4,2])
>>> p1=poly([6,3,7,2,8],[8,4,2,1])
>>> p2=p+p1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
p2=p+p1
File "poly.py", line 31, in __add__
p=p+p[Dec2[i]]
IndexError: list index out of range
>>> #The numbers in the first list is the coefficients and the second list is for degrees
這不起作用工作!但是,當我在不使用類方法的情況下完成添加時它就起作用了。我是一名初學者,我盡力解決這個問題。
另一個問題是如何寫我的代碼def str?我真的不知道我應該在一開始寫什麼。我很抱歉,但我是編程新手,需要一個簡單的代碼,比如我的代碼。
不是說它導致你的特定問題,但要小心使用'[]'作爲默認值在'__init__'(或其他地方,就此而言):http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – lvc 2012-04-28 23:04:52
此外,它可能會更有意義將多項式存儲爲係數的單個列表,以便'x^3 + 2'具有係數'[1,0,2]'。 – lvc 2012-04-28 23:18:25
我都做過了!首先我的init沒有[],但它不起作用。所以我會騎它。對不起,沒有提到我期待用戶輸入一個字符串! – user1354396 2012-04-28 23:45:36