15.15 Median


#1

Can somebody please explain to me why code doesn't work.

This is my code:

def median(numbers):

    numbers.sort()

    lenght = len(numbers)

    if lenght % 2 == 0:
            first = numbers[lenght / 2]
            second = numbers[first - 1]
            even_med = (first + second)/ 2.0
            return even_med
        
    elif lenght % 2  == 1:
        odd_med = numbers[(lenght-1)/2]
        return odd_med

    elif len(numbers) == 1:
        return numbers[0]

I get the following error when I use this code:

Oops, try again. median([4, 5, 5, 4]) resulted in an error: list index out of range

Thank you in advance to anybody who can help.


#2

problem in this line:

second = numbers[first - 1]

first doesn't hold a index, it holds a number. in this line:

first = numbers[lenght / 2]

lenght/2 would be the index, but by the square brackets notation you use, the index used to access a number in the numbers array (the index is 2, and at 2 is 5)

so, you might want to do lenght/2-1 to get the value for second


#3

Thanks for your help with my code and about posting code in a forum.