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

I do not understand why this isn't returning 4.5?

Replace this line with your code. 
def median(lst):
    if len(lst)%2 != 0 and len(lst) > 1:
        return lst[(len(lst)-1)/2]
    elif len(lst) == 1:
        return lst[0]
        return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/2
print median([4,5,3,2])


Ignore the print in the code, that was just for testing



return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/2

if the list is [4,5,5,4] you would get:

(4 + 5 ) / 2

the problem is dividing two integers in python2 results in a integer (the number is floored if need be)

How do you think we can overcome this problem now you know the cause?


Thanks for the reply,
something to do with a introducing float() from looking online,
tried it and it didn't work


what is the difference between 2 and 2.0? float() is also possible, if so, how do you think this should be done?


One is an integer and one isn't, not really sure how to use float, but i think it changes the data type from int to decimal?


i would say one is a integer and the other is a float. If you divide an integer by a float, you will get a float as result


when i divide by a float it gives 4.0?


no, 4.5

The thing is with dividing two integer (9 / 2), python thinks: i have 4.5, but then realizes you divided two integers, so floors the number for you

if you divide by a float, the floor doesn't happen


if i add this to my code it still gives 4.0,
return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/float(2)
return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/2.0


so this:


will give you index 1, which contains 4. the left one of the middle indexes so far so good.


this will give index 3, which is 5. but then you subtract one, making 5 into 4.

i think you need to subtract one while still trying to get the index so you get index 2, the middle right item


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.