It says median([4, 5, 5, 4]) returned 4.0 instead of 4.5

I don't know what I am missing

def median(items):
    x = sorted(items)
    length = len(x)
    if length % 2 == 0:
        even = (x[length/2] + x[(length/2) - 1])/2
        even = x[int(length / 2)]
    return even


in python2, dividing two integers (9/2) gives a integer as a result, if needs be, the number is floored.

try using float() to cast to a float, or divide by a float (2.0), this way, the number is not floored


If the denominator is already an integer, leave it as one and cast the numerator. Implicit floats are so misleading...

In Python 2 we could influence floats two ways. Implicitly in our data (by making sure that at least one piece of data is a float) or explicitly by passing a number to the float() method. Python 3 removes this responsibility and instead wants us to explicitly declare integers.

Something to get used to, on the one hand, but also not an issue. We can for a large part use v3 code in v2 with no side effect. Learn them both is all I can suggest to any learner.


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