The convolution between integers and floats stems from my working through the lesson in my Python IDLE, which is Python 3 and the lesson itself which is Python 2. My code is NOT optimized for Python 2.
int((((len(sequence)) / 2.0) - .5))
For this line, I force the float division then subtract by 0.5 in order to get the actual index number for the
I have to do this because
len() returns the number of items in a list instead of the index of the last item. So for
sequence = [1, 2, 3, 4, 5],
5, then I divide by
2.0 to get
2.5, but the actual median item is at index
2. Remember this is all to find the index of the median value, which has to be in integer form, so I convert the forced float back to an integer.
If I didn't force the float division, then in Python 2
len(sequence)/2 would return
2 but in Python 3 it would return
Optimized for Python 2, my code looks like this:
sequence = sorted(sequence)
if ((len(sequence) % 2) > 0):
return sequence[len(sequence) / 2]
return (sequence[len(sequence) / 2 - 1] + sequence[len(sequence) / 2]) / 2.0
I still have to divide by a float (or use
float()) in the
else: portion but it is overall much easier to read and understand.