15. median


#1



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

def median(x):
    s = sorted(x)
    l = len(x)
    a = 0
    if l == 1:
        return s[0]
    elif l % 2.0 == 0:
        m = s[l / 2.0]
        e = s[1 + l / 2.0]
        d = m + e
        return d / 2.0
    elif l % 2.0 != 0:
        f =  s[l / 2.0]
    return f


#2

this:

s[l / 2.0]

this will make the index you try to access a float, use 2 so you get an integer.

goes for all points where you try to access the list by index


#3
e = s[1 + l / 2]

like this?
but... Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5


#4

you have the list [4,5,5,4] the length is 4. so the indexes are: 0, 1, 2,3

so the two indexes you need are: 1 and 2, in other words: s[l] and s[l-1]

l-1, not plus one


#5

but i get this...
Oops, try again. median([4, 5, 5, 4]) resulted in an error: list index out of range


#6

i missed the divided by two:

s[l/2] and s[l/2-1]

Even moderators make mistakes.


#7

i still get an error...

def median(x):
    s = sorted(x)
    l = len(x)
    a = 0
    if l == 1:
        return s[0]
    elif l % 2.0 == 0:
        m = s[l / 2]
        e = s[l / 2 - 1]
        d = m + e
        return d / 2.0
    elif l % 2.0 != 0:
        f =  s[l / 2.0]
    return f

#8

^, but here:

f =  s[l / 2.0]

you still use a float to try accessing an index


#9

thanks i changed that 2.0 to 2
thank u


#10