Median issue (5/2=2?)


#1



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


I keep getting the following error:
Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

So for debugging reasons, I've tried to see what values my individual arguments would return.
The following line will return 5 (which is what I expect it to return)

return  x[(len(x)/2)]

However, dividing this argument by 2, will somehow result in 2 being returned instead of 2.5.
I tried making this a float but then it will just return the value 2.0.
So now I'm kinda stuck just wondering what kind of sorcery this is

My code:


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


#2

well, if you want a float as result, the division should involve a float:

13 / 2.0

if you do the division first, and then cast to float:

float(13 / 2)

the damage has already been done. The number is rounded down, and then cast to float (which is too late)


#3

I see, that's where I went wrong indeed.
Thanks for the quick reply! It works like a charm now


#4