# 15. Median

#1

15. Median

Oops, try again. median([1]) resulted in an error: list indices must be integers, not float

``````Replace this line with your code.
import math

def median(lst):
sorted(lst)
if (len(lst) % 2) == 0:
return (lst[len(lst) / 2] + lst[len(lst)/2 + 1]) / 2
else:
return lst[math.ceil(len(lst) / 2)]``````

#2

It tells you what the problem is though. Do you understand all the terms in that error message? If not, you'll need to ask/otherwise find out

#3

I think my list indices are integers as I divided by 2, not 2.0. Does anyone know where the problem is? Thanks.

#4

You would not be getting that error message if that was the case. You are using a float as an index. You just need to find out where. You can do that by printing out the indexes before you use them

#5

return lst[int(math.ceil(len(lst) / 2))]
but that's not all mistakes))

remember that the numbering of an array begins with 0;)

#6

My edited new code is below:

import math

def median(lst):
slst = sorted(lst)
if (len(slst) % 2) == 0:
return (slst[int(len(slst)/2)] + slst[int(len(slst)/2 + 1)]) / 2
else:
return slst[int(math.ceil(len(slst) / 2))]

But here is the new error message:
Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

#7

I warned you... that the numbering of an array begins with 0

You sorted you list to [4,4,5,5] and took 2nd and 3d elements

#9

Yes, and also I changed the indices to float.

#10

I have this but it still does not give the right value:
Error:
Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

``````def median(z):
z=sorted(z)
if (len(z))%2==0:
median = z[len(z)/2]+z[(len(z)/2)-1]
return (median/2)
else:
return z[len(z)/2]``````

#11

Never mind, I figured it out!!

``````def median(z):
z=sorted(z)
if (len(z))%2==0:
median = z[len(z)/2]+z[(len(z)/2)-1]
return median/2.0 %this was the key!
else:
return z[len(z)/2]``````

#12

Yes, it should be float.

#13

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