Median - I can't understand why I'm getting an error


15 - Median

I'm getting an error like so:

    Traceback (most recent call last):
  File "python", line 24, in <module>
  File "python", line 13, in median
IndexError: list index out of range

Line 13 is:
med = (l[one] + l[two]) / 2.0

I would think it would work, but I just can't figure it out.

def median(numbers):
    #first sort the numbers in order
    l = sorted(numbers)
    #variable to store the median
    med = 0
    #even number of numbers or odd?
    if len(l) % 2 == 0:         #even
        one = l[len(l) / 2]
        two = l[len(l) / 2 - 1]
        med = (l[one] + l[two]) / 2.0
        print one, two, med
        return med
    else:                       #odd
        med = l[len(l) / 2]
        return med
numbers = [4,5,5,4]


what do one and two contain? the numbers in the list or the indexes? the numbers, so you don't need to use them as indexes, you can just add one and two together, and divide it by 2.0


..... and it was so obvious when you wrote it down.

Thank you, problem solved.


i added a print statement:

print one, two
med = (l[one] + l[two]) / 2.0

this way you can see what is happening, that helps for debugging


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.