sampy
sampy

Reputation: 303

IndexError: list index out of range. Why do I get this error in the second function but not the first function?

The function derivative computes the derivative of a polynomial; the degree of each entry needs to be reduced by one, each entry must be multiplied by the previous degree, and the term at degree[0] needs to be removed.

This code

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)

produces this:

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

This code:

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)

produces this error:

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

So, I figured it out. Here is my new, working function, renamed ddx2:

lst = [0,3,5,4] #lst represents the polynomial 4x^3+3x^2+5x
def ddx2(lst):
    for i in range(len(lst)):
        lst[i] = lst[i]*i
        if i != 0:
            lst[i-1] = lst[i]
    del lst[-1]
    print lst
ddx2(lst) #Here I call the function

When I call the function, I get the correct derivative in the correct format, i.e. [3,10,12]. I think the error message I was getting was because I was trying to shorten the length of the list before I exited the loop.

Upvotes: 2

Views: 132

Answers (3)

Joseph
Joseph

Reputation: 71

Here is a quick hack I did :) Hope it meets your requirements, you just gotta be aware of lists length.

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!

Upvotes: 0

DomTomCat
DomTomCat

Reputation: 8569

the index i with its computation i = degree*(i+1) will grow equal or larger than len(poly) and len(copy) and hence out of range

Upvotes: 0

m9_psy
m9_psy

Reputation: 3386

The line i = degree*(i+1) basically means squared index. You have array of length i, but trying to get element with index i*i.

Upvotes: 2

Related Questions