15/15 Median


#1

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):
sequence.sort()
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 ,


#2

/ 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


#3

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 :
Article

Thank for your help !


#4

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