Remember the SectionΒ 8.4? Many algorithms involving lists make use of this pattern to process the items in a list and compute a result. In this section, weβll explore the use of the accumulator pattern with lists.
Next, the program iterates over the list (lines 2-3), and updates the sum on each iteration by adding an item from the list (line 3). When the loop is finished, total has accumulated the sum of all of the items in the list.
Sometimes when weβre accumulating, we donβt want to add to our accumulator every time we iterate. Consider, for example, the following program which counts the number of names with more than 3 letters.
The update step happens in two parts. First, we check to see if the name is longer than 3 letters. If so, then we increment the accumulator variable long_names (on line 4) by adding one to it.
We can also use == to execute a similar operation. Here, weβll check to see if the character we are iterating over is an βoβ. If it is an βoβ then we will update our counter.
We can also use the accumulation pattern with conditionals to find the maximum or minimum value. Instead of continuing to build up the accumulator value like we have when counting or finding a sum, we can reassign the accumulator variable to a different value.
In the for loop, we check to see if the current value of n is greater than the current value of best_num. If it is, then we want to update best_num so that it now is assigned the higher number. Otherwise, we do nothing and continue the for loop.
You may notice that the current structure could be a problem. If the numbers were all negative what would happen to our code? What if we were looking for the smallest number but we initialized best_num with zero? To get around this issue, we can initialize the accumulator variable using one of the numbers in the list.
The only thing we changed was the value of best_num on line 2 so that the value of best_num is the first element in nums, but the result is still the same!
Here, the accumulator variable is result. Each time through the loop, the program concatenates the current contents of result with the comma separator and a score from the list, and updates the result with the new value. Use CodeLens to step through this example to see it in action.
The output of the program has some undesirable formatting problems: there is a trailing comma instead of a period, and there are no spaces between the items. The next activity lets you work to correct those problems.
scores = [85, 95, 70]
result = ''
for score in scores[:-1]:
result = result + str(score) + ', '
# Now, append the last score
result = result + 'and ' + str(scores[-1]) + '.'
print("The scores are " + result)
This solution works by iterating over all of the scores in the list except the last, and dealing with that one separately.