Median


#1



Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5
I know this error is something related to float, but not able to get through it. Hints would be helpful. Thanks!


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


#2

Divide by 2.0 to force it in to a float.


#3

I tried
med = float((lst[mid-1] + lst[mid])/2.0)
Still the same error


#4

Found the problem. I had the sorted lst stored in a. But for the actual calculations I was still using 'lst'
Here's the final code.

def median(lst):
    a = sorted(lst)
    print a
    med = 0
    if len(a)%2 == 0:
        mid = len(a)/2
        med = (a[mid-1] + a[mid])/2.0
    else:
        mid = (len(a)+1)/2
        med = (a[mid-1])
    print med

median([1,5,2,3.3])

Thanks @alan-redding


#5

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