Stuck in median


median([4, 5, 5, 4]) returned 5.0 instead of 4.5

return 4.5

def median(list1):
    a = sorted(list1)
    if len(a) == 1:
        b = a[len(a)-1]
        return b
    elif len(a)%2 == 0 and len(a) > 1:
        b = len(a)/2
        return ((list1[b]+list1[b-1])/2.0) 
        b = len(a)/2.0
        return list1[b]



return ((list1[b]+list1[b-1])/2.0)

the median is the sum of the middle two value divide by 2 of a sorted list

list1 isn't a sorted list.

i mean, you sort the list, which is good. So you should use that here instead of the unsorted list


Thank you so much for pointing out my silly mistake!!


silly mistakes are easy to make and difficult to find

I assume its all sorted now? :slight_smile:


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