15/15 Median


Hello Everyone,

This code seems to work when I test it in other websites such as https://repl.it/repls/RealisticRowdyJaguar, but seems to not working when I run it in the CodeAcademy console.

I get the error : “median([4, 5, 5, 4]) returned 4 instead of 4.5”, whereas i get 4.5 as a result in repl.it. Any idea why ?

Here is the code :

def median(sequence):
z = len(sequence)
z = int(z)

if z == 1:
return 1

elif z == 0:
return 0

elif z%2 == 0: # is even
a = sequence[z%2] # low
b = sequence[(z%2)-1] # high
median_even = (a+b)/2
return median_even

elif z%2 != 0: # is not even
median_impair = sequence[int(z/2)]
return median_impair

x = [4,5,5,4]
print (median(x))

Best regards ,


/ behaves differently for ints in python2 and python3

Essentially you’re using integers but expecting a float result, but you’re getting an integer result.

You can “fix” it by adding from __future__ import division at the top of the file. Ideally, you should use print statements to track down what’s happening if for no other reason than that it’s a good exercise in debugging


Thanks for the info. I didn’t know about these differences !
I found that on internet that explains the topic, if that can be of any use for other readers :

Thank for your help !


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