Matthew Hrehirchuk, Eric Chalmers, Charlotte Curtis, Patrick Perri
Section7.5The Accumulator Pattern
One common programming “pattern” is to traverse a sequence, accumulating a value as we go, such as the sum-so-far or the maximum-so-far. That way, at the end of the traversal we have accumulated a single value, such as the sum total of all the items or the largest item.
In the program above, notice that the variable accum starts out with a value of 0. Next, the iteration is performed 10 times. Inside the for loop, the update occurs. w has the value of current item (1 the first time, then 2, then 3, etc.). accum is reassigned a new value which is the old value plus the current value of w.
This pattern of iterating the updating of a variable is commonly referred to as the accumulator pattern. We refer to the variable as the accumulator. This pattern will come up over and over again. Remember that the key to making it work successfully is to be sure to initialize the variable before you start the iteration. Once inside the iteration, it is required that you update the accumulator.
We can utilize the range function in this situation as well. Previously, you’ve seen it used when we wanted to draw in turtle. There we used it to iterate a certain number of times. We can do more than that though. The range function takes at least one input - which should be an integer - and returns a list as long as your input. While you can provide two inputs, we will focus on using range with just one input. With one input, range will start at zero and go up to - but not include - the input. Here are the examples:
We can use the accumulation pattern is count the number of something or to sum up a total. The above examples only covered how to get the sum for a list, but we can also count how many items are in the list if we wanted to.
In this example we don’t make use of w even though the iterator variable (loop variable) is a necessary part of constructing a for loop. Instead of adding the value of w to count we add a 1 to it, because we’re incrementing the value of count when we iterate each time through the loop. Though in this scenario we could have used the len function, there are other cases later on where len won’t be useful but we will still need to count.
n = int(input('How many odd numbers would you like to add together?'))
thesum = 0
oddnumber = 1
---
for counter in range(n):
---
thesum = thesum + oddnumber
oddnumber = oddnumber + 2
---
print(thesum)
Create a string of numbers 0 through 40 and assign this string to the variable numbers. Then, accumulate the total of the string’s values and assign that sum to the variable sum1. Note that, although the value 10 will be added to the string, it will be summed as 1 + 0, as the loop merely looks at one digit at a time.