Median


#1



Hi Pythagorians,

My code for the median exercise returns this error:
"Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5"

Thanks for your suggestions.:slight_smile:


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


def median(list_of_num):
    a = sorted(list_of_num)
    b = len(a)
    c = b-1
    d = int (c/2)
    e = d + 1
    if b % 2 == 0:
        f = (list_of_num[e] + list_of_num[d]) / 2
        return f
    elif b % 2 != 0:
        return list_of_num[d]


#2

here:

f = (list_of_num[e] + list_of_num[d]) / 2

there are two problems, list_of_num is not a sorted list.

The division involves two integers, so python will round the result down. To overcome this problem, the division should involve a float


#3

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