Traversal and accumulation
The loop patterns over an array: sum, product, count, mean, minimum and maximum with their index, the “all” and “at least one” flag, and above all the right starting value of the accumulator.
- 27 cards
- 6 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- The numbers
- Scenarios
- Understand
A few cards from the deck
Accumulator: what is it?
Show the answer
A variable that holds, pass after pass, the partial result of a calculation over the items seen so far: sum, product, count.
It is set before the loop, then updated on every pass:
s = s + x. Forgetting it or resetting it inside the loop is the classic mistake.What does this program print?
```python
t = [-3, -7, -1]
m = 0
for x in t:
if x > m:
m = x
print(m)`0-1-3-7
Show the answer
0No item is greater than 0:
mkeeps its starting value, which is not in the array. The real maximum is -1, andm = t[0]gives it.A sum starts at … and a product at …, since those are the neutral elements of addition and multiplication.
Show the answer
A sum starts at 0 and a product at 1, since those are the neutral elements of addition and multiplication.
The first pass must give
xunchanged:0 + xand1 * xarex. With 1 for the sum or 0 for the product, the whole result is wrong.Neutral element: what is it?
Show the answer
A value that leaves the result of an operation unchanged: 0 for addition, 1 for multiplication.
It is the natural starting value of an accumulator. A product started at 0 stays 0 whatever the items are.