University of Free Knowledge
QA 76.73 · fol. 15

One Pass, One Accumulator

A single pass through a sequence with an accumulator variable can find the maximum, count matches, or search for a value. · 12 min

Three questions come up over and over: what is the largest value here, how many values meet some test, and is a particular value present at all. Each has the same shape of answer. You keep one extra variable — an accumulator — that remembers what you have found so far. You set it before the loop, update it as you look at each value, and read it once the loop ends. One walk across the sequence, one variable carried along: that single pattern solves finding a maximum, counting matches, and searching.

Guess before you learn

You will scan a list of test scores to find the highest one, carrying a variable best. What should best hold before the loop looks at anything?

THE DEPTH DIAL — the same idea, younger or deeper
9–12

9–12

An accumulator carries a running result across a single loop: you initialize it before the loop, revise it from each element, and read it after. The three staple scans share this skeleton. Maximum: seed best with the first element, then if x > best: best = x. Count: seed count = 0, then if test(x): count += 1. Search: seed found = False, then if x == target: found = True — and you may stop early with break once found. Each visits every element at most once, so the work grows linearly with the length. The subtle part is always the seed: the starting value must be correct for a sequence of any contents, including empty or all-negative.

accumulator

A variable set before a loop and updated on each pass, so that after the loop it holds the result — a running maximum, a running count, or a found flag.

12before the loop: set the accumulatorfor each value: maybe update itafter the loop: read the answer
PLATE I The accumulator pattern: initialize, update each pass, then read — the shape behind max, count, and search.

Take the maximum first. Seed best with the first value so it starts as a real candidate. Then walk the rest: on each value, ask if value > best, and when that is true, replace best with the value. Values that are smaller change nothing. By the time the loop reaches the end, best has climbed to the largest value it ever saw, because any value bigger than the running best became the new best the moment you met it. Read best after the loop, and that is your maximum.

Trace the maximum of [3, 9, 2, 7] — the steps fade as you master them

1
Seed best with the first value. What is best before the walk of the rest?
best = 3
2
Next value is 9. Is 9 > 3? If so, best becomes 9. What is best now?
9 > 3 is True, so best = 9
3
Next value is 2. Is 2 > 9? Update only if true. What is best now?
2 > 9 is False, so best stays
4
Last value is 7. Is 7 > 9? What is best now?
7 > 9 is False, so best stays
5
The loop is done. What maximum does best hold?
best
Retrieval Gate — answer before you continue 0 / 4

1.Why seed best with the first value instead of 0 when finding a maximum?

2.What does best hold at the end? `` nums = [4, 1, 8, 6] best = nums[0] for x in nums: if x > best: best = x print(best) ``

3.In the maximum scan, what happens on a pass where the current value is smaller than best?

4.In one sentence, what are the three parts of the accumulator pattern?

Counting reuses the very same skeleton with a different seed and update. Set count = 0 before the loop — zero is the honest starting count, because you have counted nothing yet. Then on each value, test it, and when it passes, do count = count + 1. Values that fail the test leave the count alone. After the loop, count is how many values passed. Searching is the third variation: seed found = False, and on each value ask if value == target: found = True. If you only need a yes-or-no answer, you may break out the instant you set it.

VALUE SEENIS IT EVEN?COUNT AFTER THIS PASS4yes17no110yes23no2
PLATE II Counting the even values in [4, 7, 10, 3]: count starts at 0 and rises by 1 only on a pass that passes the test.

Ink That Thinks — guess first; the answer draws itself.
Put the steps of the find-the-maximum algorithm into a correct order.

  1. set best to the first value in the sequence
  2. look at each of the remaining values in turn
  3. if the current value is greater than best, set best to it
  4. after the loop ends, best holds the maximum
Reorder, then commit.
PLATE III The maximum scan as an ordered algorithm — guess in graphite, truth in ink.
Retrieval Gate — answer before you continue 0 / 4

1.What does this print? `` nums = [5, 2, 8, 2, 9] count = 0 for x in nums: if x > 4: count = count + 1 print(count) ``

2.Why is count seeded with 0 rather than the first value when counting matches?

3.What does this print? `` nums = [3, 7, 4] found = False for x in nums: if x == 7: found = True print(found) ``

4.Match each scan to the accumulator it starts with.

find the maximum
count the matches
search for a value

One pass, one carried variable — that is the engine under a surprising amount of everyday code. The three scans differ only in what the accumulator starts as and how each pass revises it: a running best for the maximum, a running tally for the count, a yes-or-no flag for the search. Get the seed right and the update honest, and the answer is waiting when the loop ends. The final folio turns to what happens when it is not waiting — when the program stops with an error — and how to read that error and fix it on purpose.

Practice — new ink and old, interleaved

1.What does this print? `` nums = [6, 2, 9, 4] best = nums[0] for x in nums: if x > best: best = x print(best) ``

2.score = 72. if score >= 90: g='A' / elif score >= 70: g='B' / elif score >= 50: g='C' / else: g='F'. What is g?

3.What does this print? `` nums = [1, 2, 3] nums[0] = 9 print(nums) ``

4.What does this print? `` total = 0 for i in range(4): total = total + i print(total) ``

5.What prints? `` n = 10 if n % 2 == 0: print('even') else: print('odd') ``

6.Review from folio 1: put these lines in the order they run.

  1. print("Ready?")
  2. answer = input()
  3. print("Go!")

7.For nums = [12, 5, 20, 8], what is len(nums)?

8.How many values are below 5? `` nums = [3, 8, 1, 5, 4] count = 0 for x in nums: if x < 5: count = count + 1 print(count) ``

9.What is the value of 3 > 1 and 2 > 5?

10.Why does if x = 5: raise an error where if x == 5: does not?

The Call Slip — search everything Ctrl·K / ⌘K