# 15. Praise Makes Perfect -find the error

#1

Hi all, I am receiving the following error message: Oops, try again. median([6, 8, 12, 2, 23]) returned 6 instead of 8

the math is correct and I don't find a formal error in the code. Although from the error message I see that the code must have an error under the else loop, I am unable to identify the error, any ideas?

``````def median(numbers):
numbers.sort()
if len(numbers) % 2 == 0:
middle = len(numbers) / 2
median = ((numbers[middle] + (numbers[middle - 1])) / 2.0)

elif len(numbers) == 1:
median = 1

else:
middle = int((len(numbers) / 2) - 0.5)
print middle
median = numbers[middle]
return median``````

#2

for lists with odd number of items, the length divided by 2 gives the middle index, why subtract 0.5?

#3

odd number (e.g. list of length 7) divided by 2 = 3.5, so I subtract 0.5 to make it 3 (which equals to list[3] of a 7 number list. the third indexed number then would be the middle number. Am I wrong?

#4

yea, because diving an integer by an integer in python2 will result in a integer:

``print 7 / 2``

because you subtract 0.5, you get 2.5 which then gets floored because of `int()`

#5

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