15/15 Why is it returning 5.0


#1

I can't figure out why my code is returning with this:

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

def median(nums):
n = sorted(nums)
print n, 
length = len(n)
print length, 
for x in n:
    if length % 2 == 1:
        return n[(length + 1) / 2 - 1]    
    else:
        upper = n[(length + 2) / 2]
        lower = n[(length) / 2]
        end = ((upper + lower) / 2.0)
        return end

print median([4,5,5,4])

I've sseen someone ask the same question but I didn't know how to translate the answer to my code.


#2

same!
my code is:

def median(fuc):

lst = sorted(fuc)
if len(lst) % 2 != 0 and len(lst) > 2:

return lst[(len(lst) + 1) / 2]

>elif len(lst) < 2:
    >>return 1

>else:
    >>new_median = lst[len(lst)/2] + lst[len(lst)/2 + 1]
    >>return new_median / 2

and i was told median([4, 5, 5, 4]) returned 5 instead of 4.5 TAT


#3

I found my errors, one of which was the exact same as mine. But also two other errors. this is your code fixed.

  • your first error you is what I hada problem with too. However, you had done it twice.
you entered:
len(lst)/2 + 1
the correct is:
len(lst)/2 - 1

Remember, lists count their indices from 0. Assuming you did this to find the upper value like me, this is, remembering indices positions this is doing the opposite.
You also made this mistake under you if statement.

  • You second error was dividing:
    new_median / 2
    correct way is:
    new_median / 2.0
    This is because you were dividing with an integer which rounds. Using 2.0 floats the equation making decimal answers able.
    Lastly, like my code that I found heaps of unnecessary stuff in (for x in n:), your elif is doing nothing I don't think.
    This is your code in working state:
def median(fuc):
lst = sorted(fuc)
if len(lst) % 2 != 0 and len(lst) > 2:
    return lst[(len(lst) - 1) / 2]


else:
    new_median = lst[len(lst)/2] + lst[len(lst)/2 - 1]
    return new_median / 2.0

print median([4,5,5,4])

I think that's it :smile: