15. median: stuck on [4,5,5,4]

#1

This might be something really simple but I've been stuck for a while and can't find what's up. My code is returning the error "Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5". Any advice?

``````def median(lst):
in_order=sorted(lst)
length=len(in_order)
if length%2==0:
mid1=in_order[length/2-1]
mid2=in_order[length/2]
return float((mid1+mid2)/2)
else:
midpoint=int(length/2)
return in_order[midpoint]``````

#2

Hi, @celhai ,

What happens here if the middle values in the sorted list are `4` and `5`? ...

``return float((mid1+mid2)/2)``

#3

Ok, let us use the same example, `lst = [4, 5, 5, 4]`.

Now, the calculated values are:

``````mid1 = 4
mid2 = 5``````

Returned value is `float((mid1+mid2)/2)` => `float((4+5)/2)` => `float(9/2)` => `float(4)` => `4.0`.

It's too late to change the value to float after dividing. You need to do something earlier

#4

an easy way:
def median(num):
num=sorted(num)
s=len(num)
for i in num:
if s%2==0:
return (num[s/2]+num[s/2-1])/2.0
else:
return num[s/2]

print median([3,1,5])
print median([2,3,1,5])

#5

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