Median error


#1



I wrote this code on Jupyter notebook so that I could iterate through and get it working properly. I then c/p into codecademy and it doesn't respond the same way. I get the error:


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


While when I input the same list into Jupyter it returns the correct answer (4.5)

Here is my code:


def median(numbers):
    numbers = sorted(numbers)
    me = 0
    while me ==0:
        if len(numbers) == 1:
            me= float(numbers[0])
            return (me)
        elif len(numbers) ==2:
            me = float((numbers[0]+numbers[1])/2)
            return (me)
        elif len(numbers) > 2:
            numbers.pop(0)
            numbers.pop(-1)
    print (me)

Any idea why this might be happening?


#2

let me guess, Jupyter runs python3?

changes where made to division behavior:

# python2
print 9 / 2 # 4
# python 3
print 9 / 2 # 4.5

see the difference?


#3

lol. good point!
So my guess is that there is an int somewhere that needs to be a float? But I've got that operator on the division line so I'm not sure what else would need to change.


#4

which operator?

on this line:

me = float((numbers[0]+numbers[1])/2)

you first add 4 and 5 together, this gives 9. then you divide 9 by 2, which will cause the number to be round down (so 4), then you cast to float. Which is too late so to speak, the damage has been done already. A float should be used during the division


#5

True. I removed the outermost brackets and it worked out great. Thanks!


#6

I'm actually getting a similar problem, accept mine keeps returning 2.0 instead of 4.5


#7

please go here and make a new topic, provide all the details the template ask for so we can help you


#8

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