Median in Codecademy doesn't match my Spyder result


#1



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

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

But when I run it in Spyder (the IDE I use), it returns 4.5
Am I missing something? Why is it not running correctly in Codecademy?

Full disclosure, I know that my code is probably really ugly and possibly inefficient, but it returns the correct answers for me.


def iseven(number):
    if number%2==0:
        return True
    else:
        return False
        
def median(nums):
    nums==nums.sort()
    if iseven(len(nums))==True:
        index1=((len(nums)/2)-1)
        index2=index1+1
        return (nums[int(index1)]+nums[int(index2)])/2
    elif iseven(len(nums))==False:
        return nums[int(((len(nums)/2)-.5))]


#2

SOLVED:

I changed every instance of 2 to 2.0 and 1 to 1.0
It has to do with rounding and floats and what have you


#3

let me clarify something for you, codecademy uses python 2.7

in python 2.7 a integer (non decimal number) divided by a integers gives a integer. This behavior was changed in python3. dividing integers gives a float if needed in python3. If you want to mimic python2 behavior in python3, you need to use //, which would floor the number.

Which explains why you need 2.0 in codecademy, since a integer divided by a float gives a float as result. I guess the environment you used, use python3.

Hope that clarify's something.