PyCharm Gives a Different Result than Codecademy


#1

This is the code I wrote:

def median(numbers):
    l = sorted(numbers)
    count = 0
    for x in l:
        count += 1
    while count > 2:
        del l[0]
        del l[count-2]
        count -= 2
    if count == 2:
        return (l[0] + l[1]) / 2
    else:
        n = l[0]
        return n
        

Here on codecademy I get the error: median([4, 5, 5, 4]) returned 4 instead of 4.5

But when I try this In PyCharm I get 4.5

When I try the solution in PyCharm, I get this error: TypeError: list indices must be integers or slices, not float

I have python 3.6 on my PC.

Is one of them bugged or are the different python versions to blame?


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

Hi @devpro45694,

The different results are due to how Python 2 and 3 handle division differently. If you convert l[0] and l[1] to floats before dividing them, your program will work fine in Python 2 as well :slight_smile: