15/15 - How come division doesn't seem to work?


#1

So I had this code...

def median(numbers):
numbers = sorted(numbers)
if len(numbers) % 2 == 0:
index1 = int((len(numbers)-2)/2)
index2 = int(len(numbers)/2)
number1 = numbers[index1]
number2 = numbers[index2]
result = (number1 + number2)/2
else:
index = int((len(numbers)-1)/2)
result = numbers[index]
return result

... and for some reason it just wouldn't work for lists with an even length. I kept getting an error message that [4, 5, 5, 4] was returning a median of 4 instead of 4.5. I checked each stage of the process and the numbers were computing fine... it was at the division stage that things were going wrong (e.g. for [4, 5, 5, 4], it was taking 4 + 5 and dividing that by 2, but for some reason the answer was coming out as 4 rather than 4.5). I changed the '/2' to '*0.5' and suddenly the code passed. Could someone please explain to me why multiplying by 0.5 works, but dividing by 2 doesn't?


#2

If you do 9 / 2 you will get 4 because you are doing integer division, so python will give you an integer in return. You must divide by a float to get a float, a decimal, in return. So when you multiplied by 0.5, python understood that as a float and gave you the correct answer in return.