Median


#1




I get the error: Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


def median(l):
    sort = sorted(l)
    if len(sort) == 1:
        return sort[0]
    if len(sort) % 2 == 0:
        mid1 = (len(sort) / 2) - 1
        mid2 = len(sort) / 2 
        median = (sort[mid1] + sort[mid2]) / 2
        return median
    else:
        away_from_mid = len(sort) // 2
        return sort[away_from_mid + 1]


#2

Seems like for lists with even number of items, your division to find the median is only focused on integers. Such as the actual result is 4.5 but the way you wrote the code, it will ignore the .5 after 4 and just return a 4.

There's a way to produce a decimal value and it has something to do with how you divided your median for even list of numbers.


#3

Thanks, I think I fixed that issue but now I am getting: Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8

def median(l):
    sort = sorted(l)
    if len(sort) == 1:
        return sort[0]
    if len(sort) % 2 == 0:
        mid1 = (len(sort) / 2) - 1
        mid2 = len(sort) / 2
        median = (sort[mid1] + sort[mid2]) / 2.0
        return median
    else:
        away_from_mid = len(sort) // 2
        return sort[away_from_mid + 1]

#4

OK, so if we sorted the list [6, 8, 12, 2, 23] that the error showed above, it would look like this: [2, 6, 8, 12, 23]. This means that you're returning 1 index after the expected/correct median.


#5

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