Max, min, average, count-if. Four algorithms the exam names by heart — and all four are the accumulator wearing different hats. Build them from scratch and you own a whole category of questions.
Watch how each algorithm is just a traversal with a different update rule. Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs. Traversal (3.8) walks a list; the accumulator (3.4) tracks a result. Today those combine into the four algorithms the CED names explicitly — the ones that show up again and again in multiple choice.
The exam loves these because they’re short, they combine everything, and they have one classic trap: starting the accumulator at the wrong value. Get the setup right and the loop is easy.
All four share the accumulator’s three positions — only the initialize and update change:
| Algorithm | Initialize | Update (each element x) | Use after |
|---|---|---|---|
| sum | total = 0 | total += x | total |
| count-if | count = 0 | if test: count += 1 | count |
| max | biggest = list[0] | if x > biggest: biggest = x | biggest |
| average | total = 0 | total += x | total / len |
biggest = 0. But
if every value is negative — say [-5, -2, -9] — nothing ever beats 0, so
the program wrongly reports 0 instead of -2. The fix: initialize to
the first element of the list, list[0], which is guaranteed to be a real
value. Same logic for min.
biggest = nums[0] # NOT 0 for x in nums: if x > biggest: biggest = x print(biggest)
biggest ← nums[1] /* first element */ FOR EACH x IN nums { IF (x > biggest) { biggest ← x } } DISPLAY(biggest)
Hover or tap a line to light its twin. Note the index flip in line 1: Python’s
first element is nums[0], AP’s is nums[1] — but both mean
“start from a real value in the list,” not 0.
Enter a list and see all four results at once — plus a live demo of the max trap: compare
the correct max to the buggy “start at 0” version. Try a list of all
negatives.
total / len).Five questions, several in pseudocode. Watch the initialization especially — that’s the trap. Then pick your answer.
Highest temperature this week, lowest price found, average rating, how many reviews are 5 stars — every stat on every dashboard is one of these four algorithms over a list. Sports records, weather extremes, class averages, “how many liked this”: max, min, average, count-if, again and again.
The initialization trap is a real-world bug, too. A temperature tracker
that starts lowest = 0 will never report a below-zero reading — it’ll
insist the coldest day was 0°. Starting from a real data point instead of a convenient number
is a habit that separates code that works on your test case from code that works on everyone’s
data.