Median - median([4, 5, 5, 4]) returned 4 instead of 4.5


#1

def median(lst):
    lst = sorted(lst)

    if len(lst) % 2 == 0:
        x = int(len(lst) / 2)

        y = (lst[x-1] + lst[x]) / 2
        return y
    else:
        x = (len(lst) / 2) + 0.5
        y = int(x - 1)
        return lst[y]

#2

By the way , it works just fine in my local python3.4


#3

A couple of things could be improved. First, when the list is even. If it's even, but the list has maybe 6, 8, etc elements, your

x = len(lst) - 2

statement will not work (remember you want halfway through the list, so maybe instead of subtracting two, try something else to get you into the middle). The other thing, which is why you are getting 4, is because you are dividing an int by another int, which gives you an int. This is hard for a newer programmer to find, but ints automatically round down because they cannot have values after decimal points.

If the list is 4 numbers long, it is really doing

(lst[1] + lst[2]) / 2
(4 + 5) / 2
9 / 2
4

It rounds down. Instead of

y = (lst[x-1] + lst[x]) / 2
return y

try something like this, by making 2 a floating point number (also save a line doing this)

return (lst[x-1] + lst[x]) / 2.0

The other issue is when the list is odd. Think about the issue from above in your

x=

line. You can change 1 thing to make that line work (same issue as above)


#4

Thanks for the reply,

sorry i copied old version of my code so instead of (x = len(lst) - 2) I use x = int(len(lst) / 2)

What I could not understand is why my code run just fine in my local python3,4 environment .

is it something different in python versions or whatever


#8