sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
I get that these sections of code are indices for the two middle integers in the list. And that they are being added together so we can return the average in the next line. But why are the preceding lst required?
if len(lst) % 2 == 0:
Can anyone explain what the “%” function actually does? How it works etc
That is called a parity check, or a check for evenness. The mdoulo operator, % indicates remainder division. If a number divided by 2 has no remainder, then the number is even.
This relates to a statistics concept, median which is the middle of a sorted sample list. If the list is even-length, then we need to draw out the middle two indexes; if odd we use only the single middle index.
It’s not the integers that we are drawing out, but the indexes for those elements. Once we have the two middle indexes we can poll the values, add them and take their average as the median.
Note that in this exercise we are not sorting the list, only finding the physical middle of the list, not the median.
We can see in the earlier example that rather than repeat len(lst) / 2 or 1en(lst) we cache those values in n and m.
n = len(lst) # n will be an integer
m = n // 2 # because we use integer (floor) division, m is an integer
Now with this information all we need to determine is the parity of the length so we know whether to return one term, or the average of two.
if n % 2:
return float(lst[m - 1] + lst[m]) / 2