# 15.median

#1

hi...i don't know what is wrong with my code...it returns 5.0 instead of 4.5.

``````Replace this line with your code.
def median(lists):
result = 0
lst = sorted(lists)
if len(lst)%2 == 0:
result = result+(lst[len(lst)/2]+lst[(len(lst)/2)+1])/2.0

elif len(lst)%2 != 0:
result = result + int(lst[(len(lst)/2)])
return result
print median([4, 4, 5, 5])``````

#2

well, if we have the following list: `[4, 4, 5, 5]`, the indexes are: 0, 1, 2 and 3. So the middle two indexes are 1 and 2, but according to the math you do here:

``lst[len(lst)/2]+lst[(len(lst)/2)+1]``

the middle two indexes are 2 (`len(lst)/2`) and 3 (`len(lst)/2+1)`

#3

OMG...
I can't believe i forgot that in python indexes start from 0...
thanks a lot...
i changed result = result+(lst[len(lst)/2]+lst[(len(lst)/2)+1])/2.0 to
result = result+(lst[(len(lst)/2)-1]+lst[(len(lst)/2)])/2.0
and it got fixed.

#4

yep, that is quit important to remember

lists and strings are zero indexed based in python (and many other languages)

#5

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