Sorted


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096

It says my code returns 4 instead of 4.5 but when I run the script in Python IDLE on my PC it does return the correct 4.5.


I would like to know what is wrong with the syntax to cause an error on Codecademy. Thanks!


def median(lst):
    lst.sort()
    if len(lst) % 2 == 0: #even list
        return(((lst[len(lst) // 2 - 1] + lst[len(lst) // 2])) / 2)
    else: #odd list
        return(lst[len(lst) // 2])


#2

your computer probably has python3 installed, codecademy uses python2

A huge difference is that in python2, a integer divided by a integer returns a integer, while this behavior was changed in python3, dividing two integers can now give a floating result:

9 / 2 = 4.5 // python3
9 / 2 = 4 //python2

to overcome this problem in python, you could divide by a float (2.0) or use float() to cast it to a float


#3

print median([1,2,3,4])

returns 2 instead of 2.5 for me (not in Codecademy).

I think you should divide sum of elements by 2.0, not 2.

print 5/2 # 2
print 5/2.0 # 2.5

#4

@arkussss please see my explanation


#5

I think I replied 2 seconds after you.


#6

i wasn't talking about the timing, i was explaining why 9 /2 could give two different results (4 and 4.5)


#7

Ok. I know why it could give two different results, but didn't know that in Python3 9/2 will return 4.5. I used to use Python 2.7, that's why I replied that @skillville should divide by float.


#8

and

that sounds like contradicting things to say. He should indeed divide by a float, or use float(), i absolutely agree with you on that


#9

I know why 9/2 and 9/2.0 will give different results in Python 2.7 :slight_smile: Dividing integer by integer returns integer, but dividing integer by float returns float.


#10

I tried to divide by 2.0:
def median(lst):
lst.sort()
if len(lst) % 2 == 0: #even list
return ((lst[len(lst) // 2 - 1] + lst[len(lst) // 2]) / 2.0)
else: #odd list
return (lst[len(lst) / 2.0])

The error now is" Oops, try again. median([1]) resulted in an error: list indices must be integers, not float"
suggestions?


#11

for your odd lists there was no reason to change 2 to 2.0, since then we are talking about indexes of lists

@arkussss, like so. That make sense. And now you also know 9 / 2 = 4.5 in python3. If you want to mimic python2 behaviour in python3 you will need:

9 // 2 # 4, the number will floored

#12

I got it, simply type float in front of the last return statement. THANKS GUYS :slight_smile:
def median(lst):
lst.sort()
if len(lst) % 2 == 0: #even list
return ((lst[len(lst) // 2 - 1] + lst[len(lst) // 2]) / 2.0)
else: #odd list
return float(lst[len(lst) / 2])


#13

no need to use float, since odd list will simple pick the middle number there is no need