Median: adjusted code per error request, but don't understand how it is correct


#1


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

Oops, try again. median([6, 8, 12, 2, 23]) resulted in an error: list indices must be integers, not float

For median([6, 8, 12, 2, 23]) for example, I expected that cutting a list of 5 numbers in half - 2.5 - and then subtracting by 0.5 would create an index of 2, which is what number 12 is in the list: list[2] = 12. However, Python sees the 0.5 and interprets the result as a float somehow, instead of interpreting the result of subtracting a float to create a whole number.

outcome = 0
sorted_list = sorted(list)

odd_middle = (len(sorted_list) / 2) - 0.5      ##this divides the odd numbered length list by 2, which gives you a half              number. So you subtract 0.5 to get a whole number, and the index that you want the code to return. For median ([6, 8, 12, 2, 23]) - a list of 5 numbers: (5/2=2.5) - 0.5 = 2. index[2] = 12.

if len(sorted_list) % 2 == 0:
     ## code for averaging two middle indices 

else:
     outcome += sorted_list[odd_middle]

#2

but in python2, dividing two integers:

5 / 2

results in a integer (2), the number is floored by python


#3

That answers my question! Thank you.


#4