My code works in Python 3 for the input [4,5,5,4]. However, on codecademy, the output of my code is 4 instead of 4.5 and I have no idea why. Any help would be appreciated.
def median(x):
x.sort()
q = int(len(x)/2)
r = len(x)
if r%2==0:
y = x[q] + x[q-1]
return y/2
elif r%2!=0:
h = x[int(q-.5)]
return h
oops it doesn’t work on python 3 either
It’s because in python 3.* the /
symbol became float division while in python 2.* it is floor division. You just have to switch it to //
for 2.*.
Thanks zeziba! I fixed the problem by applying floor() to the divisor