Median


#1

Excercise:

Error message:
Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

What did you expect:
i expect this line, result = s[(len(s) / 2)] + s[(len(s) / 2) -1], to calculate the index for the two middel values and add them togheter to later devide them by 2. however doesnt seem to work.

def median(x):
    s = sorted(x)
    result = 0
    if len(s) == 1:
        result = s[0]
    elif len(s) % 2 == 0:
        result = s[(len(s) / 2)] + s[(len(s) / 2) -1]
        result /= 2
    else:
        result = s[(len(s) // 2) + 1 / 2]
    return result

#2

so this line of code:

result = s[(len(s) / 2)] + s[(len(s) / 2) -1]

result would be 9, make sense? however dividing two integers in python2 gives an integer in return (the number is floored if needs be)

try dividing by 2.0, this way you will get a float in return


#3

that did the trick, thanks. One last question, if the value get floored in the elif statment how come it doesnt get floored in the else statement. seeing that the else statement would be X.5 is it becuase i add a 0.5?


#4

it does? which is a good thing, indexes can only be integers.

in case of if statement, you add two numbers together (5 and 4)(this are not indexes) which you then have to get the middle value (4.5). this shouldn't be floored.


#5

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