Why is my median incorrect?


#1

Question

Why is my median incorrect?

Answer

Finding the median of a list of numbers can be especially difficult if it’s an even number of numbers. To ensure that you’re actually working with the values you think you are, it can be very helpful to print them all out at each step. For example, when you sort your list, print your_sorted_list to see if it worked. When you calculate the midpoint, print your_midpoint to see if it’s the value at the middle index, or if it’s the middle index.
Half the battle is knowing what you’re working with at each step of the way. There are so many approaches to this particular problem that it’s not very meaningful to try and guess what could be wrong in your particular implementation. However, it will always be helpful to print your code out in steps, as that’s a major part of debugging!
Once you know what your values actually store, then you can proceed to make necessary changes with everything we’ve learned so far.


FAQ: Learn Python - Practice Makes Perfect - median
#2

Because the interface’s answer is wrong. The solution prints the median where 4 and 5 are in the middle, in which the answer is 4.5. However, the interface inputs 5 and 5 in the middle, but still thinks the answer is 4.5, even though it would just be 5 (5 + 5 = 10 / 2 = 5).


#3

The answer is 4.5 because they say to sort the list. This changes [4, 5, 5, 4] to [4, 4, 5, 5].