Need help as why it is giving error when the code is returning correctly


Oops, try again.
median([4, 5, 5, 4]) returned 5.0 instead of 4.5 getting this error message but the requirement is to find the median of middle two numbers. In this list the middle two numbers as 5,5 and their average will be 5 then why it is expecting the average as 4.5

need to know why I am getting the above error and what am i doing wrong here

def median(items):
    length = len(items)
    if length %2 == 0:
        firstValue = items[(length/2)-1]
        secondValue = items[length/2]
        return (firstValue+secondValue)/2.0
        middle = length/2
        return items[int(middle-1)]
print median([4,5,5,4])


I found the reason. i missed the sorted sequence due to which i am getting error. once I sorted the input numbers then it is giving the correct output without errors


First step in simplifying a problem is to simplify the code. length/2 occurs three times in the sample code, a case for caching. In a zero indexed structure the middle is the same in both parities. As it were, the upper of the middle pair in even case. We know that the lower of this pair is one index to the left.

The idea here is to do the heavy lifting outside of the selection process which can be done with two lines, given a sorted list. x...

n = len(x)
m = int(n / 2)

Now we can build a return value...

return x[m] if n & 1 else float(x[m - 1] + x[m]) / 2

>>> x = sorted([6,4,2,5,4,2,1])
>>> n = len(x)
>>> m = int(n / 2)
>>> x[m] if n & 1 else float(x[m - 1] + x[m]) / 2


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