Median


#1



Median


It says : "median([4, 5, 5, 4]) returned 4 instead of 4.5 ". Nevertheless, I tried to test the code in Python shell and it returns 4.5. What am I doing wrong?


 def median(x):
    z = sorted(x)
    if len(x) % 2 == 0:
        mid = int((len(x) / 2))
        y = (z[mid] + z[mid - 1]) / 2
        return y
    else:
        y = z[int(len(x) / 2 - 0.5)]
        return y


#2

your shell runs python3, changes where made to division behavior:

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

to get a float in python2, the division should involve a float


#3

Thanks. Didn't even know that division in python2 works this way. :sweat_smile:


#4

yep, which means here:

y = z[int(len(x) / 2 - 0.5)]

you don't have to do -0.5, to write code which works for both version use floor division (//) this will floor (round down to nearest integer) the number


#5

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