Median


#1



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


When I use this code I always get this error message:
Oops, try again. median([1]) resulted in an error: list index out of range


It's meant to return the median of the numbers in the list, but I'm not sure what's wrong with the code.


def median(lst):
    nlst = sorted(lst)
    if len(nlst) % 2 == 0:
        ind = len(nlst) / 2
        med = float((nlst[ind-1] + nlst[ind])/2)
    else:
        ind2 = (len(nlst)+1) / 2
        med = nlst[ind2]
    return med


#2

here:

ind2 = (len(nlst)+1) / 2

why plus one? length divided by 2 gives the middle index for odd lists, if you don't believe me, do the math


#3

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