15 Median: list index out of range


#1

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

Please help me with my code! The error message says that the list index is out of range. Also, when I call median([1,2,3,4,5]), it did not return 3 but 4. I don't know why.

def median(numbers):
    median_number = 0
    sort = sorted(numbers)
    count = len(sort)
    if count % 2 == 0:
        median_number = (sort[count] + sort[count + 1]) / 2.0
    else: 
        median_number = sort[(count + 1) / 2]
    return median_number
    
print median([1,2,3,4,5])

#2

here:

median_number = (sort[count] + sort[count + 1]) / 2.0

count is the length which given lists are zero indexed based is already an index error, count + 1 is also index error

How would you go about calculating the middle indexes based on the length? I can tell you: length is not the middle index


#3

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