15. Median - Median([1]) List Index Out of Range


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#

I'm not sure what I am doing wrong, but the error message is "Oops, try again. median([1]) resulted in an error: list index out of range."

I have printed my own list, and it gives back the correct median. Here is my code:

def median(sequence):
    sequence = sorted(sequence)
    ls = len(sequence)
    #
    if ls > 1:
        middle = ls/2
        middle_2 = ls/2 - 1
    elif ls == 1:
        middle = sequence[0]
    #Begin calculation of median if even num list
    if ls % 2.0 == 0:
        center = (sequence[middle] + sequence[middle_2]) / 2.0
    else:
        center = sequence[middle]
    return center
    
print median([1,2,3,4])


Any help is much appreciated! I'm sure/hoping it's a small mistake.


#2

The special case can be returned directly.

return sequence[0]

Notes

The above is the equivalent of,

sequence.sort()

In both cases, the original list is sorted.

Eg.

def sort_shallow(sequence):
    return sorted(sequence)

def sort_static(sequence):
    sequence.sort()

original = [9,1,8,2,7,3,6,4,5]

shallow = sort_shallow(original)

print shallow                     # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print original                    # [9, 1, 8, 2, 7, 3, 6, 4, 5]

sort_static(original)

print original                    # [1, 2, 3, 4, 5, 6, 7, 8, 9]

#3

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