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

I don't know what's wrong with my code I should return the proper number but for some reason it just gives the error message

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


indices is plural of index

When you access a value in a list by index, that index must be an integer, it cannot be a float. You cannot do this:

[1, 2, 3][1.5]

There is no one-point-fiveth element in that list.

Next you'll want to identify where this occurs, you can do that by reproducing the bug and looking for a line number in the error message that the interpreter prints. You may also be able to identify the location by just knowing what the problem is and looking at the code, considering where you could be doing that.


you are awesome thanks


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