I'm always .5 off with my final answer. Where am I not correctly making my number an integer?

In the example [4,5,5,4] I expect 4.5, but it produces 4

mylist = [1,1,2]
def median(mylist):
    mylist = sorted(mylist)
    listlength = len(mylist)
    if listlength % 2 == 0:
        return (mylist[int(listlength/2 + .5)] + mylist[int(listlength/2 - .5)]) / 2
        return mylist[int(listlength/2 + .5)]


if the division involves two integers python will round the number down, make sure you involve a float in the division so the number isn't rounded down to a integer


Got it. I ended up going with the Band-Aid solution of always adding +.5 to the variable at the end, which works... but didn't explain to me what was going on. Thanks.


That really is a band aid solution, look:

print 9 / 2 # 4
print 9 / 2.0 # 4.5

see the difference? If there are two integers, python will round down to a integer, if there is a float involved, it won't happen. Try to implement this without doing +.5


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