# Practice makes perfect: median

#1

Hi team,

can anyone tell me what is wrong with my code ?

it should print 4.5 as the result but instead, it gives me 6.

Thanks,
Ruolan

#2

can you copy paste your code to the forum? visual debugging is very difficult

#3

hi there,

``````def median (lst):
lst = sorted(lst)
if len(lst) %2 == 0:
array_s = lst[len(lst) / 2 - 1]
array_b = lst[len(lst) / 2]
median = array_s + array_b / 2

else:
median = lst[(len(lst) - 1) / 2]

return median
``````

like this?

#4

Be sure to cast a float as your result when the list length is even.

``float(a + b) / 2``

#5

thaankkkkkk you sooooo muchhhhhhhh!!

#6

order of operations, you have to use parentheses, otherwise division goes before sum and casting to float like mtf says.

#7
``````def median (lst):
lst = sorted(lst)
if len(lst) %2 == 0:
array_s = lst[len(lst) / 2 - 1]
array_b = lst[len(lst) / 2]
median = float(array_s + array_b )/ 2

else:
median = lst[(len(lst) - 1) / 2]

return median

print median([4,5,5,4])

``````

thank you so much!!! now it works!!! appreciated the help!!

#8

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