15/15 Median Error


#1

from math import ceil 
def median(lst):
    lst = sorted(lst)
    x = len(lst)
    if x == 1:
        return lst[0]
    elif x % 2 == 0:
        a = x / 2.0 
        b = x + 1
        return int((lst[a] + lst[b]) / 2.0) 
    elif x % 2 != 0:
        m = x / 2.0
        n = round(m)
        o = ceil(m)
        return int((lst[n] + lst[o]) / 2.0)

Getting the error code: 'Oops, try again. median([4, 5, 5, 4]) resulted in an error: list indices must be integers, not float.'

Also, can someone explain why the hint tells you to use floats..?


#2

Yeah make sure that any indexes you use are integers, floats are not allowed. It doesn't make sense to use floats anyway, because indexes are exact, they aren't approximations (floats approximate numbers)

No rounding, no ceiling, they should never ever be floats because that doesn't make sense even if you convert them back to integers later.

So stick to integer operations for computing indexes, and in general avoid floats unless they really are what you need (approximations of numbers) or you don't mind if they might be slightly off.

You can do integer division like this:
5 // 2 # result is 2

And in Python2 that's actually the default anyway, so this has the same result:

5 / 2 # result is 2

But that changes in Python3, and it's nice to show your intentions to the reader with //

Slightly off might be a really big deal if you for example ceil 5.00000000000001 - that's the kind of stuff that happens if you treat them as exact values. Or if you try to test if it's equal to 5, well, it's not, so don't ever test if a float is equal to anything either, because, again, that doesn't make sense when you're dealing with approximations, they won't be equal, they'll be approximately the same, which is pretty complicated to test so again it's better to use integers if you want to do that kind of thing.