# Median in practice makes perfect

#1

the error comes
Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

Nothing seems to be wrong in my code

``````def median(lost):
lost.sort()
w=len(lost)
if w%2==0:
c=(lost[w/2]+lost[(w/2)+1])/2
else:
c=lost[w/2]
return c``````

#2

the problem is this line:

``c=(lost[w/2]+lost[(w/2)+1])/2``

I think it is a good method you are using, one tiny problem. lets do an example, lets say i take the list `[4,5,5,4]`, after it is sorted, the list is is `[4,4,5,5]`. So lost[w/2] is index 1, holding number 4, and lost[w/2]+1 is index 2, holding 5. `4 + 5 / 2 = 4`. Because all numbers are integers (non decimal numbers) the result is also a integer (if the result is a decimal, the result will be floored)

How to overcome this problem? Either use `float()` or divide by a decimal number (for example `2.0`)

#3

Thank you much for the help but the problem still persists...

``````def median(lost):
lost.sort()
w=len(lost)
if w%2==0:
c=float((lost[w/2]+lost[(w/2)+1]))/2.0
else:
c=lost[w/2]
return c``````

ERROR:-
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

#4

okay, the sorted list of of [4, 5, 5, 4] is [4, 4, 5, 5]. The items are indexed at 0,1,2 and 3 (arrays are zero indexed based), and the length of the list (in your case a variable called `w`) is 4 (since it has 4 items)

so we want to have the values at index 1 and 2 (make sense)? So w/2 = 2 (index 2, which is good). w / 2 + 1 = 3. Ouch, wrong one. That should be w / 2 -1, you want to have the item at index 1

#5

Thanku so much stetim94. My problem got solved.