Median problem


#1

hi, i need help with that code.

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

return the folowing problem:
Oops, try again. median([4, 5, 5, 4]) resulted in an error: list indices must be integers, not float
thank's


#2

You can't do this:

[1, 2, 3][1.5]

You may only use integers as indexes for a list


#3

ok, i understand it, but when i fix it the next error is:
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5
and i couldn't figure out what is the problem...


#4

Irrelevant, I found the problem. (Changed from minus to plus in the second if)!
thank you very much for the help! :slight_smile::slight_smile:


#5

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