15/15 - Median - error in even list


#1

Hi all, here's my code of which I get the error:
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

I guess the problem might be due to the sorted function, but I'm not sure.
I checked the usage of the sorted function and it looks like that it changes the original list, so I don't see the
problem in my code....

Help? :smiley:

def median(lst):
lstSize = len(lst)

# Sort the list
sorted(lst)

if not lstSize % 2 == 0:
    # If the size of the list is odd, just return the median
    # To find the index of median - remove 1 from the list size and divide by 2
    return lst[(lstSize-1)/2]
else:
    # The size of the list is even
    # To find the index of median - divide the list size by 2 and take this index
    #      plus the index - 1
    return (lst[lstSize/2] + lst[(lstSize/2)-1])/2.0

#2

In python 2.7.* / means to ceil divide, // means to floor divide.

a = 2 / 3
b = 2 // 3

You have to make one number a float to get what you want.

return (lst[lstSize/2.0] + lst[(lstSize/2.0) - 1])/2.0

#3

It's strange, because when I've changed my code to the following - it worked:
I've just entered the result of sorted to another variable and use it in the rest of my code...

I'm not sure why it worked and didn't in the old code.

def median(lst):
lstSize = len(lst)
newLst = []

# Sort the list
newLst = sorted(lst)

if not lstSize % 2 == 0:
    # If the size of the list is odd, just return the median
    # To find the index of median - remove 1 from the list size and divide by 2
    return newLst[(lstSize-1)/2]
else:
    # The size of the list is even
    # To find the index of median - divide the list size by 2 and take this index
    #      plus the index - 1
    return (newLst[lstSize/2] + newLst[(lstSize/2)-1])/2.0

#4

The sorted function does not sort the original list. It is used to create a "new" sorted list from a given list.

In the new code, you correctly use sorted by creating a new list.