What is wrong with this



What is wrong with this code??

def median(lists):
    if len(lists)%2==0:
        return lists[midval]
        return (lists[midval]+lists[midval-1])/2


The even and odd case need to be swapped, and integer / 2 returns an integer.

If len(lists) % 2 == 0 is True, that means you're dealing with a list containing an even number of items. In that case you need to divide the two middle values. But you did that in the else case!

When Python is dividing integers it will round to keep the result an integer. Use decimal places to show that you want a float result.

print 3 / 2   # 1
print 3 / 2.0 # 1.5


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