Solution Design First, check if the numbers list is empty and, if so, return None. Next, you must sort them by
calling the sort() list method. Then calculate the middle index by integer dividing the list length by
2
. Integer division does normal division and then rounds the result down to the next lowest integer.
Python’s integer division operator is //. So, for example, while the expression 5 / 2 evaluates to
2.5
, the expression 5 // 2 evaluates to 2.
Next, figure out if the list length is odd or even. If odd, the median number is at the middle
index. Let’s think about a few examples to make sure this is correct:
If the list length is 3, the indexes range from 0 to 2 and the middle index is
3 // 2
or 1. And 1 is the middle of 0 to 2.
If the list length is 5, the indexes range from 0 to 4 and the middle index is
5 // 2
or 2. And 2 is the middle of 0 to 4.
If the list length is 9, the indexes range from 0 to 8 and the middle index is
9 // 2
or 4. And 4 is the middle of 0 to 8.
These seem correct. If the list length is even, we need to calculate the average of the two middle
numbers. The indexes for these are the middle index and the middle index minus 1. Let’s think about
a few examples to make sure this is correct:
If the list length is 4, the indexes range from 0 to 3 and the middle indexes are
4 // 2
and 4 // 2 - 1, or 2 and 1. And 2 and 1 are the middle of 0 to 3.
If the list length is 6, the indexes range from 0 to 5 and the middle indexes are
6 // 2
and 6 // 2 - 1, or 3 and 2. And 3 and 2 are the middle of 0 to 5.
If the list length is 10, the indexes range from 0 to 9 and the middle indexes are 10 // 2
and 10 // 2 - 1, or 5 and 4. And 5 and 4 are the middle of 0 to 9.
These seem correct too. Even-length lists have the additional step that the median is the average
of two numbers, so add them together and divide by two.