15.Median , Help Please


#1



python

Replace this line with your code.

def median(N):
m = 0
N = sorted(N)
l = len(N)
if l > 1:
if l % 2 != 0:
m += N[(l-1) / 2 ]
elif l % 2 == 0:
m += int((N[l/2-1] + N[l/2]) / 2)
elif l == 1:
m += N[0]
return m

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


#2

here:

m += int((N[l/2-1] + N[l/2]) / 2)

this would result in:

9 / 2

the problem is, because the division involves two integers, the number is floored (rounded down), to solve this problem, use a float somehow, try if you can figure it out. (either a decimal number or use float() to convert to float)


#3

Thanks for your reply, without int also I got the same error and I can't solve it :frowning:


#4

that can't be, can i see an updated version of your code?

make sure that in the division one of the numbers is a float, if you cast to float after the division the damage (rounding down) has already been done


#5

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

def median(N):
    m = 0.0
    N = sorted(N)
    l = len(N)
    if l > 1:
        if l % 2 != 0: 
            m += N[(l-1) / 2 ]
        elif l % 2 == 0:
            m = m + (N[(l/2)-1] + N[l/2]) / 2
    elif l == 1:
        m += N[0]
    return m

#6

here:

(N[(l/2)-1] + N[l/2]) / 2

the division still only involves integers? No floats to see


#7

It's solved, float should be just for numbers


#8

got it Thanks a lot for your help


#9