15. Median


#1

I am getting error for this code:
def median(lst):
nwlst = sorted(lst)
count = len(nwlst)
if count == 1:
return nwlst[count - 1]
elif count > 1:
if count % 2 != 0:
return nwlst[((count + 1) / 2) - 1]
else:
val1 = nwlst[count / 2]
val2 = nwlst[(count / 2) - 1]
avg = (val1 + val2) / 2
return avg

{Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5}
Can anyone explain?
Indentation is correct in console,


#2

It looks as though the problem is a result of data types. If you remember the int data type only stores whole numbers. To get a number with a decimal you need to use the float data type. In this case you need to change the second to the bottom line so that your math is being done with floats. Here is what that line should look like:
avg = float((val1 + val2)) / 2