Median


#1

def median(w):
    a = sorted(w)
    b = len(a)
    for i in a:
        if b % 2 == 0:
            m = (a[b/2] + a[b/2-1]) / 2.0
        else:
            m = a[round(b/2)]
        return median

This code gets the following error:

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


#2

what is wrong with it?


#3

Let us assume that w = [1], so b = 1, right?

Problem occurs in this line:

m = a[round(b/2)]

b / 2 = 1 / 2 = 0, but rand(0) = 0.0, so you have a float number. This is how round works. All indices are integers so you have to use integers. And the question is, do you really need to use round in this line?


Extra note. Please check if the return statement is in the correct place and whether the returned value is correct.


#4

Thank you :slight_smile: :heart_eyes:


#5

You're very welcome :panda_face:


#6

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