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

Expected to return 4.5. Need help.

def median(x):
    if len(a)%2!=0:
        return (a[int(len(a)/2)]+a[int(len(a)/2)-1])/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


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.


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.

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


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.


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


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.


Got it. Thanks for the help.