Median


#1


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


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


I am unable to understand why the list is not being sorted before it looks any further to find the median. it might be something stupid but I guess I am missing it.


 def median(lst):
    lst_1=sorted(lst)
    length=len(lst_1)
    for i in lst_1:
        if length==1:
            return lst[0]
        elif length%2!=0:
            return lst_1[(length+1)/2]
        elif length%2==0:
            med1=lst_1[length/2]
            med2=lst_1[(length/2)+1]
        return (med1+med2)/2


#2

No need offor loop.

While checking list having odd number of items ,
We need to do this... (length -1)/2 ,Lists are 0-indexed.

You have to do same changes in last elif part!


#3

Thank you. It really was a silly mistake, and yeah, i did change the last elif part.
my updated code looks like below and it works great.
def median(lst):
lst_1=sorted(lst)
length=len(lst_1)
if length==1:
return lst[0]
elif length%2!=0:
return lst_1[(length-1)/2]
elif length%2==0:
med1=lst_1[(length/2)-1]
med2=lst_1[(length/2)]
return (med1+med2)/2.0


#4

A post was split to a new topic: Getting the median result as 5.0 instead of 4.5


#5

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