Median, I don t understand what I am missing


#1



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


I can t find the mistake


def median(numbers):
    list_num = sorted(numbers)
    if len(list_num) % 2 == 0:
        numb = len(list_num)
        return float((list_num[numb / 2 - 1] + list_num[numb / 2])/2)
    elif len(list_num) == 1:
         return list_num[0] 
    else:
        numb = len(list_num)
        return list_num[(numb - 1) / 2]


#2

i get a different error message:

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

The problem is that dividing two integer:

9 / 2

will cause python to floor the number (round down)

yes, you use float(), but too late, given the number is already rounded down and then you cast the number to float

The division itself should involve a floating number


#3

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