15. median


#1

def median(x):

a = sorted(x)

if len(a) % 2 == 0:
    middlea = 0.5*(a[0.5*len(a)]+a[0.5*len(a)-1])
    return middlea
elif 1 in a:
    return a[0]
else:
    return a[len(a)/2]

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


What's the matter..?


#2

This expression yields a float.

One way around this issue would be to cache the length before any testing.

n = len(a)
m = int(n / 2)

Now we can use m as an index.


#3

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