Median


#1



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


Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

Expected to return 4.5. Need help.

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


#2

Hi @bytecoder29837,

Are you performing int or float division as the final operation here? ...

return (a[int(len(a)/2)]+a[int(len(a)/2)-1])/2

#3

hello @appylpye
It should return a float value. Shouldn't it?
I have also tried to convert the value to float but the same error keeps popping up.


#4

Codecademy uses Python 2.x, so the / operator performs int division if both operands are int objects. You are dividing the sum of the two middle items by 2, so if those items are both int objects, the result is an int.

Post the line in which you tried converting to float.


#5
    return float((a[int(len(a)/2)]+a[int(len(a)/2)-1])/2)

#6

In the above, you converted to float after the final division. Instead, you need to convert the numerator to float prior to that division. Check the arrangement of the parentheses.


#7

thanks. that solved the problem but i wonder why does putting the float all over the value didn't work.


#8

If you perform the division prior to converting to float, you get int division if both operands are ints. Converting the whole expression to float does not affect the intermediate operations; it only performs the conversion after all the other operations have occurred. Any fractional part, such as .5, gets lost during an int division. Converting to float after that has already happened does not recover the lost fractional part.


#9

Got it. Thanks for the help.


#10