15. Median


#1

When I submit this, I get "median([1]) resulted in an error: list index out of range". I'm not really sure why. Am I missing something?

def median(x):
    y = sorted(x)
    if len(y) % 2 == 0:
        a = len(y) / 2
        return ((y[a] + y[a + 1]) / 2)
    else:
        b = ((len(y) + 1) / 2)
        return y[b]

#2

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]  # int(9 / 2) == 4
             [4]
              5                => median == 5


[ 1, 2, 3, 4, 5, 6, 7, 8 ]
          [3][4]
     float(4 + 5) / 2          => median == 4.5

Use this as a guide to correct your code.


#3

A post was split to a new topic: Median - I understand the problem but


#6