15/15 Unexpected result


#1

I’m getting an error claiming that if [4, 5, 5, 4] returns 5.0 instead of 4.5. Going through the code, I’ve been sprinkling in prints here and there to see where the code is getting confused, but am getting nowhere. The sorting is working fine, and I haven’t found any weird syntax problems.

def median(list):
result = 0
new_list = sorted(list)
if len(new_list) == 1:
result = new_list[0]
elif len(new_list) % 2 == 0:
result = (new_list[len(new_list) / 2] + new_list[(len(new_list) / 2) + 1]) / 2.0
else:
result = new_list[len(new_list) / 2 + 1]
return result

(I don’t know how to make make my indents show up in the forum, but I assure you, all that is fine)


#2

if the list has 4 items (thus a length) of 4, the indexes are: 0, 1, 2 and 3. So, 1 and 2 are the middle indexes, but if i then look at your calculation here:

result = (new_list[len(new_list) / 2] + new_list[(len(new_list) / 2) + 1]) / 2.0

i see you use 2 and 3 for the middle indexes


#3

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