Median - not sure where the mistake is?


#1



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


def median(lst):
    n=0
    lst_sort=sorted(lst) #4 4 5 5
    lst_len=len(lst) #4
    if lst_len % 2 != 0: # 4%2=0
        n=lst_len/2
        return lst_sort[n]
    else:
        n=lst_len/2 #4/2=2
        return (lst_sort[n]+lst_sort[n+1])/2.0 #4+5 / 2.0 = 4.5
median([4,5,5,4])


#2

For list [4, 5, 5, 4] your function goes like this:

n = 0
lst_sort = [4, 4, 5, 5]
lst_len = 4

lst_len % 2 != 0 ==> 0 != 0 ==> false, so we go to the else block

n = 2
return (lst_sort[2] + lst_sort[3]) / 2.0

Element at index 2 is the third element -> 5, and element at index 3 is the fourth element -> 5.

So (5 + 5) / 2.0 is equal to 5.0.

Second element should have another index :slight_smile:


#3

tweaked like below,

def median(lst):
n=0
lst_sort=sorted(lst)
lst_len=len(lst)
if lst_len % 2!=0:
n=lst_len/2
return lst_sort[n]
else:
n=lst_len/2
return (lst_sort[n-1]+lst_sort[n])/2.0
median([4,5,5,4])

It's working :slight_smile:

Thanks factoradic !!