This code gives me right answer on the Python installed in my computer but the wrong answer on Codecademy. Glitch or am I missing something?


For the example median([4, 5, 5, 4]) Codecademy says it returns 4 but when I run it on the Python I have installed on my computer it says 4.5 which is the right answer. Any idea what is going on? I am at a complete loss and what to move on to learn more about Python! Haha.

def median(numbers):
    sorted_list = sorted(numbers)
    midpoint = len(numbers) // 2

    if len(numbers) % 2 == 1:
        return sorted_list[midpoint]
        return (sorted_list[midpoint] + sorted_list[midpoint - 1]) / 2
print(median([4, 5, 5, 4]))


If anyone sees this in the future I figured it out. I needed to divide by a decimal to get a decimal is what I am guessing. I changed 2 to 2.0 as shown below and it worked. I guess this is just a difference between Python 2 and Python 3.
return (sorted_list[midpoint] + sorted_list[midpoint - 1]) / 2.0


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