15/15 median Error: list index out of range


#1

def median(listas):
    sort = sorted(listas)
    
    lenght = len(listas) /2
    x = 0
    if lenght%2 == 0:
        x+= (listas[lenght +1] + listas[lenght]) / 2.0
        
    else:
        x += listas[int(lenght)]
    print lenght   

    return x
print median([1])

I get error:

  File "python", line 7, in median
IndexError: list index out of range

#2
lenght = len(1) / 2
lenght = 0 (actually 0.5, but because you calculate with integers it will give an integer)

listas[lenght + 1], so actually listas[0 + 1] -> listas[1]

listas has only 1 element, and the program starts counting from 0, so you want to access a list element, which doesn't exist! :confused:

type

x+= (listas[lenght] + listas[lenght]) / 2.0

instead and it should work fine :slightly_smiling:


#3

I get error saying:
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5
:confused:(im pretty lost in this lesson)


#4

Did you type it like this:

def median(listas):
    sort = sorted(listas)
    
    lenght = len(listas) /2
    x = 0
    if lenght%2 == 0:
        x+= (listas[lenght +1] + listas[lenght]) / 2.0
        
    else:
        x += listas[int(lenght)]
    print lenght   

    return x
print median([4,5,5,4])

Because that worked in my console and gave out 4.5


#5

Did this code passed the lesson?


#6

No sorry, my bad. I used the old one with the +1 in my own console and didn't realize it :confused:

I'll do my best to correct your code so it can actually pass, give me a few minutes.


#7

Now I have made it work, and it passed the lesson. There were actually a lot of errors :wink:

def median(listas):
    sort = sorted(listas)
    lenght = len(listas)
    if lenght%2 == 0:
        return (sort[lenght/2] + sort[(lenght/2)-1]) / 2.0
        
    else:
        return sort[lenght/2]

One of your greatest mistakes was, to sort the list, but still using the unsorted list, instead of the sorted one. Just go through the code and try to understand it :smiley:


#8

Ok, thank you!
:wink: