Codecademy says code is wrong while PyCharm says it works!


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096


In Practice Makes Perfect at level 15 (median), Codecademy gives the error message "Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5" when I try to submit my code.


However, when I copy and paste my code into PyCharm and try the same exact function call (median([4,5,5,4])), it returns 4.5 as expected. Below is my code:


def median(numbers):
    numbers = sorted(numbers)
    if len(numbers) % 2 == 0:
        return (numbers[int(len(numbers) / 2)] + \
        numbers[int(len(numbers) / 2) - 1]) / 2
    else:
        return numbers[len(numbers) / 2]


#2

Alright, I understood my error by myself but I will still write it here in case someone else runs into the same situation.

The problem arises from a Python 2/ Python 3 difference, since in Python 3 an integer divided by an integer returns a float while in Python 2 it returns an integer. Since I use Python 3 in PyCharm, the code was working whereas my results were being rounded down on Codecademy.


#3

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