15. Median


What is wrong with this code.
I get "Oops, try again. median [4,5,5,4] return 1 instead 4.5, when my list is [1], I get median [1] resulted error, list index out of range (I use PyCharm and there I don`t get any error)

lst = [1]
n = len(lst)
def median(ls):

    print ls

    if n % 2 == 0:
        m = n / 2
        md = ls[m - 1] + ls[m]
        med = (float(md)/2)
        return med
        m = (n+1) / 2
        print m
        med = ls[m-1]
        return med

print median(lst)


the exercise will call the function multiply times to validate it works correctly, so anyting related to calculating the median should be inside of the function


Same happen when I put
n = len(lst)
in the function. I try list 1, and try list 4,5,5,4 and they work, but always is the same error.


can i see an updated version of your code?



n= len(lst), you should use ls here, so your function works for any list


Thanks, that work (just simple mistake that I can`t see when I was working PyCharm)