# 15. median

#1

Why is this not working? The answer should be 5.0 not 4.5, right? If I set halfLen_1 = halfLen+1 then it solves my issue with 4,5,5,4 but it creates problems further on. Sorting the list did not help.

``````Error message:
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5``````

``````def median(x):

med=0.0
length=len(x)
halfLen=length/2
halfLen_1=halfLen
#x.sort()

if length%2==0:
med=(x[halfLen]+x[halfLen_1])/2.0
else:
med=x[halfLen]

return med
#print median([1,1,2])``````

Ok, I only refreshed the page and it solved the problem I had but now it crashes at 6, 8, 12, 2, 23.

``````Error message:
Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8``````

The code is exactly the same. It should be 12, right?

#2

the median is the middle number for a sorted lists with a odd number of items, and for even numbers it are the middle two numbers of a sorted list

Important: sorted list!

if we have `[4,4,5,5]`, so then the middle two items are 4 and 5, which is 4 + 5 / 2 which is 4.5

#3

I have no idea what I did but after rewriting the code and messing around with the half of the list it somehow worked.

``````def median(x):

x.sort()
med=0
if len(x)%2==0:
med=float((x[len(x)/2-1]+x[len(x)/2])/2.0)
else:
med=x[len(x)/2]

return med
print median([1,1,2])``````

is this right?

#4

Yes, this is good.

Do you have any questions about it?

#7

No, I think I got it. Thanks.

#8