Median


#1




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):
    sorted(lst)
    if len(lst)%2 != 0 and len(lst) > 1:
        return lst[(len(lst)-1)/2]
    elif len(lst) == 1:
        return lst[0]
    else:
        return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/2
print median([4,5,3,2])


#2

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


#3

here:

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?


#4

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


#5

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


#6

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?


#7

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


#8

when i divide by a float it gives 4.0?


#9

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


#10

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)
or
return (lst[len(lst)/2-1] + lst[(len(lst)+2)/2]-1)/2.0


#11

so this:

lst[len(lst)/2-1]

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

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

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


#12

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