15. Median


#1

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


I get this message:

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

When I run python on my computer with the exact same code, and call

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

I get the result 4.5.


def median(values):
    med = 0
    values = sorted(values)
    if len(values) % 2 == 0:
        med = values[int(len(values) / 2)-1] + values[int(len(values) / 2)]
        med = med /2
    else:
        med = values[int(len(values) /2)]

    return med


#2

Never mind - change the 2s to 2.0s and it works. Odd python on my machine doesn't need that.


#3

in python2, a integer divided by a integer gives as result a integer. This behavior was changed in python3, in python3 (which i guess your machine is running) a integer divided by a integer can give a float as a result:

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

to overcome this problem, (like you discovered) you can divide by a float (2.0) or use float() to cast it to a float


#4

Thanks. Yeah, I've 3 on my machine. I thought it might be float related but as it worked on mine didn't twig mine could be different!


#6

you have a question @betaace35719? If so, please make your own topic. Thank you