# 15 - Median

#1

This is my code for finding the median of a list of numbers. It works fine for odd lists, but when I give it a even list it gives me the error "error list indices must be integers, not float" Where am I going wrong?

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

print median([1,2,3,4,5,6,7,8])``````

#2

For odd lengths you don't subscript the list so something isn't adding up in what you're describing.
The error message says what was being attempted that isn't possible, from what I can tell that answers your question. Are you wondering something else other than that? Maybe you aren't asking for what you want to know (and establishing what information you need next is pretty helpful to finding it, both when asking and when solving things by yourself)

#3

``````  0  1  2  3
[ 4, 5, 7, 9 ]
^  ^
5 + 7
12

12 / 2 == 6``````

Note that 4 / 2 is 2, which is the higher index of the two middle elements.

#4

Thanks for jogging my brain, I realized I wasn't thinking in terms of the index value and then found a ton of other mistakes.

#5

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