# 15. Median

#1

I get an error of: list indices must be integers, not float
I'm not sure what I did wrong.
Can someone help?

``````def median(lst):
lst = sorted(lst)
med = []
mn = 0
if len(lst) % 2 == 0:
med.append(float(len(lst)) / 2.0 + 0.5)
med.append(float(len(lst)) / 2.0 + 0.5)
for i in med:
mn += lst[i] / 2
return mn
return mn
else:
med.append(len(lst) / 2)
for i in med:
mn += lst[i]
return mn
return mn``````

#2

``````[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]  # int(9 / 2) == 4
[4]
5                => median == 5

[ 1, 2, 3, 4, 5, 6, 7, 8 ]
[3][4]
float(4 + 5) / 2          => median == 4.5``````

Use this as a guide to simplify your rather complex method.

#3

Thanks, I figured it out:

``````def median(lst):
lst = sorted(lst)
med = 0
if len(lst) % 2 == 0:
larger = len(lst) / 2
smaller = larger - 1
med += (lst[larger] + lst[smaller]) / 2.0
return med
else:
middle = len(lst) / 2
med += lst[middle]
return med``````

#4

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