Median problem


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

I have no idea why this doesn't work, it looks fine to me, help much appreciated

def median(x):
    x_sort = sorted(x)
    if len(x) == 1:
        return (x[0])
    elif len(x)%2 == 0:
        return (x_sort[len(x)/2-1] + x_sort[len(x)/2])/2
        return x_sort[round(len(x)/2)]


In python 2 this will be an integer when it should be a float.

There are four instances of len(x) that could be cached for simplicity...

n = len(x)

and instead of halving it three times,

m = int(n / 2)

Now see if that does not help to simplify your code.


Thank you, that does simplify my code, but I still have the same error message of the median of (4,5,5,4} is returning as 4 instead of 4.5. Even when I put float((x_sort[n/2-1] + x_sort[n/2])/2), it still returns 4.0 instead of 4.5. Very confused


Sorry, worked it out, needed to divide by 2.0 instead of 2 otherwise it automatically converts to an int. that's annoying


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