Median


#1




So, the error I'm getting is "Oops, try again. median([1]) resulted in an error: object of type 'NoneType' has no len()" so I would really appreciate some help.


def median(lists):
    sort_list = lists.sort() 
    if len(sort_list)% 2 == 0:
        middle = len(sort_list)/ 2
        middley = sort_list[middle] - 1
        median = sort[middle] + sort_list[middley]/ 2
    else:
        middle = len(sort_list)/2
        median = sort_list[middle]
    return median


#2

.sort() will return a sorted list, no need to store it in a different variable


#3

Ok so I changed that:

def median(lists):
    lists.sort() 
    if len(lists)% 2 == 0:
        middle = len(lists)/ 2
        middley = lists[middle] - 1
        median = lists[middle] + lists[middley]/ 2
    else:
        middle = len(lists)/2
        median = lists[middle]
    return median

but now the error is "Oops, try again. median([4, 5, 5, 4]) resulted in an error: list index out of range"


#4

because middley does not contain the the left middle index, it contains the number at the left middle index.


#5

Oh ok. So I did that:

def median(lists):
    lists.sort() 
    if len(lists)% 2 == 0:
        middle = len(lists)/ 2
        middley = middle - 1
        median = lists[middle] + lists[middley]/ 2
    else:
        middle = len(lists)/2
        median = lists[middle]
    return median

but now it says "Oops, try again. median([4, 5, 5, 4]) returned 7 instead of 4.5"


#6

do you take a minute to think about why this new error might arise?

here:

that should help


#7

Oh, right, thank you. So, I corrected that:

def median(lists):
    lists.sort() 
    if len(lists)% 2 == 0:
        middle = len(lists)/ 2
        middley = middle - 1
        median = (lists[middle] + lists[middley])/ 2
    else:
        middle = len(lists)/2
        median = lists[middle]
    return median

But now I'm getting "Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5". I can't see what I'm missing.


#8

dividing two integers (9 / 2) gives an integer as result, the number gets floored if needs be

try to divide by 2.0 or use float()


#9

Thank you. I used 2.0 and it works now.


#10