Median not returning correctly but does in 3rd party interpreter


#1



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


Hello,

I seem to be having an odd issue with the median problem. It says that a list returns 4 instead of 4.5, though when I run the code in a different editor it seems return 4.5 and not 4. If you run the code below in the online interpreter at https://repl.it/languages/python3 it returns 4.5.

So I guess my question is why is this returning 4 on your interpreter and 4.5 on the other?


 
def median(numbers):
  number = sorted(numbers)
   
  if len(number) % 2 != 0:
    return (number[int(len(number) /2)]) 
  else:
    return ((number[int(len(number) /2)]) + (number[int(len(number) /2 - 1)])) /2
print(median([4, 5, 5, 4]))


#2

a change was made to division behavior:

# python2 
print 9 / 2 # outputs: 4
# python3
print(9 / 2) # outputs: 4.5

to overcome this problem in python2 the division should involve a float, to prevent python from rounding down to the nearest integer.


#3

Thank you for this information! I will update the code to ensure it's a float and not an int for the proper behavior.


#4

the advantage python2 is that you can just do:

return (number[len(number) /2])

you don't need int() given python will round down to the nearest integer

personally i would prefer to use floor division (//) over int(), given floor division will round down to the nearest integer directly, where as int() has to do division first and then cast to integer


#5

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