15/15 - median


#1
def median(lis):
    result = 0
    tempLis = sorted(lis)
    if (len(lis) % 2 == 0):
        location = len(lis) / 2
        result = (tempLis[location - 1] + tempLis[location]) / 2
    else:
        location = len(lis) // 2
        result = tempLis[location]
    return result

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

I cannot see the problem, can someone help me out?
Thanks in advance


#2

Python automatically rounds down when doing integer division. I addressed the problem thats in your line
result = (tempLis[location - 1] + tempLis[location]) / 2
by using 2.0 instead of 2


#3

Ok, I'm not the only one with this problem.

I used

from fractions import Fraction

at the beginning of my function and then this to do the actual calculation:

result = Fraction((l2[(len(l2) - 2) / 2] + \
l2[len(l2) / 2]), 2)

The explanation is that for Python 2.X / does always floor division for integer numbers


#4

@unluberkay Hello, please remember to use float. I had the same problem but you need to use the float function to turn your number into decimal. In the if statement add the float() function before dividing by two.

@specialsymbol Hello, don't use function, use the float() function where turns your number into a decimal number.

Hope that helps!