Sub topic 9
Carrying State in an Accumulator
This chapter assumes you can write a simple recursive function with a base case and a recursive case. You should also know how the call stack holds one frame per active call, and be comfortable reading Python. It shows a technique called accumulator-passing style. Here the recursive function carries a partial result forward as an extra parameter, instead of combining results after each call returns.
Where the Work Happens
A plain recursive function usually does its real work on the way back up the stack. Look at factorial:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(4)) # 24When factorial(4) runs, it cannot multiply yet. It must wait for factorial(3) to return. Each frame holds a pending operation, "multiply my n by whatever comes back". The multiplications all happen after the base case is reached, while the frames unwind:
factorial(4)waits to compute4 * ?factorial(3)waits to compute3 * ?factorial(2)waits to compute2 * ?factorial(1)waits to compute1 * ?factorial(0)returns1, and then the stack unwinds:1,2,6,24
An accumulator moves that work to the way down. You add a parameter that holds the result so far, and each call updates it before making the next call:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(4)) # 24The trace now looks like this:
| Call | `n` | `acc` on entry | Work done before the next call |
|---|---|---|---|
| 1 | 4 | 1 | `acc = 1 * 4 = 4` |
| 2 | 3 | 4 | `acc = 4 * 3 = 12` |
| 3 | 2 | 12 | `acc = 12 * 2 = 24` |
| 4 | 1 | 24 | `acc = 24 * 1 = 24` |
| 5 | 0 | 24 | base case returns `24` |
No frame has anything left to do after its recursive call returns. Each one passes the base case's answer straight back up unchanged.
The Recipe
Converting a recursive function to accumulator style follows a fixed pattern:
- Add a parameter,
acc, to hold the partial result. - Give it the starting value the base case used to return:
1for a product,0for a sum, an empty list for a collection. - In the recursive case, fold the current element into
accand pass the new value to the next call. - In the base case, return
acc.
These steps map closely onto a loop. The starting value of acc matches the value you assign before a loop begins, and the update in step 3 matches the loop body. A later chapter builds on that match to turn these functions into loops mechanically.
Here is a sum over a list, written both ways. It uses an index rather than slicing, because xs[1:] copies the list on every call and turns a linear algorithm into a quadratic one:
def sum_plain(xs, i=0):
if i == len(xs):
return 0
return xs[i] + sum_plain(xs, i + 1)
def sum_acc(xs, i=0, acc=0):
if i == len(xs):
return acc
return sum_acc(xs, i + 1, acc + xs[i])
data = [3, 1, 4, 1, 5]
print(sum_plain(data)) # 14
print(sum_acc(data)) # 14Hiding the Accumulator
A default argument like acc=0 exposes an internal detail. A caller who passes a third argument by mistake gets a wrong answer and no error. The usual fix is a public function that calls a private helper:
def mean(xs):
if not xs:
raise ValueError("mean of empty list")
def go(i, total, count):
if i == len(xs):
return total / count
return go(i + 1, total + xs[i], count + 1)
return go(0, 0, 0)
print(mean([2, 4, 6, 8])) # 5.0This example also shows that you can carry more than one accumulator. total and count move forward together, and the base case combines them. Any state a loop would keep in several variables can travel as several parameters.
Order Changes the Answer
Plain recursion combines elements from the right: the last element is combined first, during unwinding. An accumulator combines them from the left, in the order it visits them. For addition and multiplication the order makes no difference, because those operations are associative and commutative. For other operations it does.
Subtraction shows the difference clearly:
def sub_right(xs, i=0):
if i == len(xs):
return 0
return xs[i] - sub_right(xs, i + 1)
def sub_left(xs, i=0, acc=0):
if i == len(xs):
return acc
return sub_left(xs, i + 1, acc - xs[i])
print(sub_right([10, 3, 2])) # 10 - (3 - (2 - 0)) = 9
print(sub_left([10, 3, 2])) # ((0 - 10) - 3) - 2 = -15Building a list shows the same effect. If you prepend each element to the accumulator, the first element visited ends up last:
def reverse_acc(xs, i=0, acc=None):
if acc is None:
acc = []
if i == len(xs):
return acc
return reverse_acc(xs, i + 1, [xs[i]] + acc)
def copy_acc(xs, i=0, acc=None):
if acc is None:
acc = []
if i == len(xs):
return acc
acc.append(xs[i])
return copy_acc(xs, i + 1, acc)
print(reverse_acc([1, 2, 3])) # [3, 2, 1]
print(copy_acc([1, 2, 3])) # [1, 2, 3]Reversal falls out of accumulator style naturally, and that is often useful. When you want the original order, append instead. In Python, [x] + acc also copies the list each time, so it costs O(n²) overall. It is shown here for clarity, not speed.
Common Errors
The mutable default argument
Python evaluates default values once, when it defines the function, not on each call. A list default is therefore shared across every top-level call:
def evens_buggy(xs, i=0, acc=[]):
if i == len(xs):
return acc
if xs[i] % 2 == 0:
acc.append(xs[i])
return evens_buggy(xs, i + 1, acc)
print(evens_buggy([1, 2, 3, 4])) # [2, 4]
print(evens_buggy([6, 7])) # [2, 4, 6] (wrong: leftovers from the first call)Use acc=None and create the list inside the function, as reverse_acc and copy_acc do, or use a private helper that the public function starts with a fresh [].
Returning the wrong thing at the base case
When you convert a function, it is easy to leave the old base case in place:
def factorial_broken(n, acc=1):
if n == 0:
return 1 # should be: return acc
return factorial_broken(n - 1, acc * n)
print(factorial_broken(4)) # 1All the work is sitting in acc. Returning the old constant throws it away.
The wrong starting value
The starting value must be the identity for your operation: the value that leaves any input unchanged. A product that starts at 0 always returns 0. A maximum that starts at 0 gives the wrong answer for a list of negative numbers. In that case, start from the first element, or from float("-inf").
Combining after the call anyway
Writing return x + f(xs, i + 1, acc) defeats the purpose. The frame again has pending work, and x is counted twice if acc also includes it. In accumulator style, the recursive call should be the last thing the function does, and its result should be returned unchanged.
What the Accumulator Does Not Fix
Accumulator style changes when the work happens. It does not change how many frames exist at once. sum_acc on a list of 100,000 elements still makes 100,000 nested calls, and CPython raises RecursionError at its default limit of about 1,000:
import sys
def count_acc(n, acc=0):
if n == 0:
return acc
return count_acc(n - 1, acc + 1)
print(sys.getrecursionlimit()) # typically 1000
print(count_acc(500)) # 500
try:
count_acc(100_000)
except RecursionError:
print("still too deep")| Aspect | Plain recursion | Accumulator style |
|---|---|---|
| When combining happens | On the way back up | On the way down |
| Pending work per frame | Yes | None |
| Combination order | Right to left | Left to right |
| Base case returns | A constant | The accumulator |
| Frames in use at peak (CPython) | n | n |
| Extra parameters | None | One per piece of state |
Exercise
Rewrite this function in accumulator style, hiding the accumulator behind a helper: def length(xs, i=0): return 0 if i == len(xs) else 1 + length(xs, i + 1)
Show answer
def length(xs): (newline) def go(i, acc): (newline) if i == len(xs): return acc (newline) return go(i + 1, acc + 1) (newline) return go(0, 0). The starting value is 0, the identity for addition. The update adds 1 before the call, and the base case returns acc instead of the constant 0.
Exercise
A student converts a string-joining function to accumulator style with the update acc + s, starting from "", and gets the strings in their original order. Another student uses s + acc. What does the second version return for ["a", "b", "c"], and why?
Show answer
It returns "cba". The accumulator visits elements left to right, and s + acc puts each new string in front of everything collected so far, so the first element visited ends up last. Concatenation is not commutative, so the update's operand order decides the output order.
Exercise
Why does calling evensbuggy([6, 7]) after evensbuggy([1, 2, 3, 4]) return [2, 4, 6], and what is the smallest fix?
Show answer
Python creates the default list once, when it defines the function, so both top-level calls append to the same list object. Change the default to acc=None and add "if acc is None: acc = []" at the top of the function, so each top-level call starts with a new list.
Exercise
Write max_acc(xs) using an accumulator so that it returns -3 for [-7, -3, -9]. Which starting value would make it return the wrong answer?
Show answer
def max_acc(xs): (newline) def go(i, acc): (newline) if i == len(xs): return acc (newline) return go(i + 1, xs[i] if xs[i] > acc else acc) (newline) return go(1, xs[0]). Starting from xs[0] (or float("-inf")) works. Starting from 0 would return 0, because no element of the list is greater than 0.