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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. The numbers
  5. Scenarios
  6. 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

    0

    No item is greater than 0: m keeps its starting value, which is not in the array. The real maximum is -1, and m = 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 x unchanged: 0 + x and 1 * x are x. 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.