# Median

#1

``````Error message:
median([4, 5, 5, 4]) returned 5.0 instead of 4.5``````

I think everything is correct, but I can't figure out why the answer isn't coming out right.

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

else:
return original[int(len(original)/2.0)]``````

#2

I would split up that really long line into smaller parts and check them individually. Might wanna start by figuring out which one was used to get the wrong result.

Appropriate things to isolate would be 1) the middle index 2) value1 3) value2 4)average of value1 and value2

The list itself by the time you look things up by index is also worth looking at, especially if the above values are correct but the result is still off

Generally just walk through what it's doing and compare to how you would be doing it manually.

#3

I broke it down a little, but I'm still getting the same error. Maybe its not sorting the list?

``````def median(old):

sorted(old)
if len(old)%2==0:
i1= old[len(old)/2]
i2= old[(len(old)/2)-1]
return (i1+i2)/2.0

else:
return old[int(len(old)/2.0)]``````

#4

It is sorting it, but then not storing the sorted list. Assign to a variable.

#5

Duh. Thanks so much!

#6

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