Stuck in median


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#


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) 
    else:
        b = len(a)/2.0
        return list1[b]


#2

here:

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


#3

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


#4

silly mistakes are easy to make and difficult to find

I assume its all sorted now? :slight_smile:


#5

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