Median Exercise


#1



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


So when I paste this code into my Python 3.6 on my computer it tells me that:
median([4, 5, 5, 4]) = 4.5

Yet when I try this code in the exercise screen it throws up the error:
"Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5


def median(x):
    y = sorted(x)
    B2 = int((len(y)/2))
    if len(y)%2 == 0:
        B1 = int((len(y)/2)-1)
        return float((y[B1]+y[B2])/2)
    else:
        return y[int(B2)]

Any help is greatly appreciated. Could this be a problem with codeacademy using a different version of Python?


#2

codecademy uses python2.7.3, and in python3 a change was to how division works:

#python3 
9 / 2= 4.5
#python2 
9 / 2 = 4

#3

THANK you. I've been stuck on this for ages


#4

Do you think you can figure out how to make it work?


#5

def median(x):
ans = 0
new = sorted(x)
if (len(new) ==1):
ans = new[0]
elif (len(new)%2 == 0):
ans = float((new[len(new)/2] + new[(len(new)/2)-1])/2)
else:
ans = new[float((len(new)/2))-0.5]
return ans

I'm in the same state and I'm not sure how to resolve.


#6

ajaxslayer43861 got it based on my hint, you need to do something with float. If you have more questions, make an new topic


#7