2016-06-07 21 views
2

功能衍生物計算多項式的導數;每個條目的度數需要減1,每個條目必須乘以先前的度數,並且度數[0]的項需要被移除。IndexError:列表索引超出範圍。爲什麼我會在第二個函數中得到這個錯誤,但不是第一個函數?

此代碼

lst = [1,2,3] """This list represents the polynomial 3x^2+2x+1""" 

"""This function moves each entry one index down and removes the last 
entry""" 

def move(lst): 
    copy = list(lst) 
    for i in range(len(lst)): 
     lst[i-1] = copy[i] 
    del lst[-1] 
    print lst 

move(lst) 

產生這樣的:

Samuels-MacBook:python barnicle$ python problemset2.py 
[2, 3] 

此代碼:

def derivative(poly): 
    copy = list(poly) 
    degree = 0 
    for i in range(len(poly)): 
     i = degree*(i+1) 
     poly[i-1] = copy[i] 
     degree += 1 
    del poly[-1] 
    print poly 

derivative(lst) 

產生這樣的錯誤:

Samuels-MacBook:python barnicle$ python problemset2.py 

    Traceback (most recent call last): File "problemset2.py", line 59, 
    in <module> 
     derivative(lst) File "problemset2.py", line 55, in derivative 
     poly[i-1] = copy[i] IndexError: list index out of range 

所以,我明白了。這是我的新的,工作職能,改名ddx2:

​​

當我調用該函數,我得到正確的衍生正確的格式,即[3,10,12]。我想我得到的錯誤信息是因爲我在退出循環之前試圖縮短列表的長度。

+2

添加一些調試語句,通過在設置爲'degree *(i + 1)'之前和之後在循環中打印'i'的值。你會看到你在做什麼。 – leekaiinthesky

+0

而不是「移動」,你可以簡單地做'my_list [: - 1]' – Ben

回答

2

該行i = degree*(i+1)基本上是指平方指數。您的數組長度爲i,但嘗試獲取索引爲i*i的元素。

+0

它更糟。 「度」與「我」相同,所以它是「我=我*(i + 1)」。 – Barmar

0

指數i其計算i = degree*(i+1)將增長等於或大於len(poly)len(copy)較大,因此超出範圍

0

這裏是一個快速劈我做:)希望它滿足你的要求,你只是愛知道列出長度。

lst = [1,2,3] 


dlist=[] 
derivate=[] 
for i in range(len(lst)): #Here you multiply the coeficients by the power 
    dlist.append(lst.__getitem__(i)*i) 
#print dlist 
for m in range(len(dlist)): #In the derivate the constants become zero 
    if dlist.__getitem__(m) != 0: 
     derivate.append(dlist.__getitem__(m)) 
print lst 
print derivate 

Enjoy!

+0

謝謝!是的,列表長​​度是我必須意識到的。我很感謝你的幫助,我真的很想在我自己的身上做這個(幾乎)。順便說一句,是不是_getitem_類方法什麼的?我還沒到那兒呢!謝謝!!! – sampy

相關問題