Median


#1



This code fails on the check when given the list: [4,5,5,4]
It raises the following error:

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

As I understand it, the median of lists of even length is the average of the two middle elements.
I'm sure the average of the two middle elements (5 and 5, in this case) of the given list is 5, not 4.5.


def median( lst ):

    mid_index = len(lst) // 2
    mid_val = lst[ mid_index ]

    # list length is even
    if len( lst ) % 2 == 0: 
        return (mid_val + lst[ mid_index - 1 ]) / 2.0

    # list length is odd
    else: 
        return mid_val

Thanks in advance for the help.


#2

Edit: I didn't realize the list was supposed to be sorted beforehand. Apologies.


#3

That would be if the list was not sorted. A median is determined on a sorted sample.


#4

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