A pencil and paper are great to have on hand for this type of problem, in terms of visualization.
[ , , , , , , , , ]
Which element or pair of elements is/are in the middle? What is its index?
sample = [ 41, 94, 38, 76, 59, 25, 19, 63, 81 ]
Count the number of elements.
n = len(sample)
Remember that the first element is index 0. Using integer (or floor) division, find the middle index (or upper pair index).
m = n // 2
In our visual above, what is the index of the middle element? What is
n is floor divided by
Thanks to fellows like Martin Richards and Edsger W. Dijkstra
we have zero-indexing offering up another advantage in that the quotient of integer division (by 2) of the length of the list either gives us the middle index, or the upper of the two middle indices.
# s = sorted(sample)
return s[m] if n % 2 else (s[m - 1] + s[m]) / 2 # 59
Note: divide by 2.0 if Python 2
One key point to remember when looking for ways to simplify is to identify and cache key data so there are no recurrent patterns. An identity will fill in where needed. Note our
n variables. There are no methods in the return statement.
I commented out the sort line because it is important for us to see (visualize) the middle element(s) of a list, whether sorted or not. Note that we cached the important data before sorting.
Consider also that the list we are computing the median of may be sensitive to changes. That’s why I use
sorted so the parameter is only copied, not mutated. That would re-order the original list and possibly cause problems somewhere else in the program. Lesson here is to never mutate a list in a function unless that is the specific intention. Finding the median of a list does not imply that intention. Best leave the argument list intact.