Median


#1



My code prints 4.5 in PyCharm, but the course program says it returns 4. It shows an error message "Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5"


def median(lst):
    lst = sorted(lst)
    if len(lst) == 1:
        med = lst[0]
    elif len(lst) % 2 == 0:
        a = int((len(lst) / 2) - 1)
        b = int(len(lst) / 2)
        med = (lst[a] + lst[b]) / 2
    else:
        a = int(len(lst) // 2)
        med = lst[a]
    return med

a = [4,5,5,4]
print(median(a))


#2

you pycharm runs python3. A change was made to division behavior in python3:

# python3
print(9/2) # 4.5
# python2
print 9 / 2 # 4

to overcome this problem in python2, use a float

python2 only floors (rounds down) when the division involves two integers


#3

Try using "2.0" in division to force float output


#4

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