15. median


#1

Hi on exercise 15, Median I wonder why in Python3 my code worksl but on codecademy with python2 I get 4 instead of 4.5 (Python3).

def median(numbers):
    nums2 = remove_duplicates(numbers)
    ia = int(len(nums2)/2)
    if len(nums2) % 2 == 0:
        p = ia - 1
        result = (nums2[p] + nums2[ia])/2
        return result
    else:
        result = nums2[int(ia/2)]
        return result

def remove_duplicates(nums):
    nums2 = []
    for n in nums:
        if n not in nums2:
            nums2.append(n)
    nums2 = sorted(nums2)
    return nums2
    

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

Median
#2

python3 has some fundamental changes, this is the crucial line:

result = (nums2[p] + nums2[ia])/2

in python2, a integer divide by integers gives a integer (the number gets floored if necessary), in python3 it will yield a float. To overcome this problem, you can simple divide by a float (2 instead of 2.0) or use float() to cast it to a float

If you want to achieve python2 behavior ( 9 / 2 = 4, you can use 9//2 = 4, the number will get floored)


#3

Why do you remove duplicates?