15. Median


#1

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)
lst.sort()
def median(ls):

    print ls

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

print median(lst)


#2

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


#3

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


#4

can i see an updated version of your code?


#5


#6

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


#7

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


#8