Medium: Interview Core · Problem 45 of 82

Running Total

MediumGenerators and IteratorsPython

Write a generator running_total(numbers) that yields the running total after each number: for [1, 2, 3, 4] it yields 1, 3, 6, 10. It must work on any iterable of numbers, including a generator, and must be lazy.

Understand the problem

Do it by hand and think about state.

What are the running totals of [5, -2, 4]? Type the list.

After 5: 5. After -2: 5 + (-2) = 3. After 4: 3 + 4 = 7. Each output is the previous output plus the new number: the generator must remember one number, the total so far.

Which statement is true for a generator that yields running totals?

  1. It must read the whole input before the first output
  2. It can output the first total as soon as it has read the first number
  3. It needs the length of the input

The running total after item k depends only on items 1 to k. A generator can yield it immediately, so the work is spread out and memory stays constant.

Write the solution

A generator function.

def running_total(numbers):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What single value must you keep between yields?

Hint 2: the shape of the answer

A variable total = 0. For each number: add it, then yield total.

Reflect

Solution

def running_total(numbers):
    total = 0
    for number in numbers:
        total += number
        yield total

Another way: itertools.accumulate

from itertools import accumulate

def running_total(numbers):
    return accumulate(numbers)

What this tests: generators with state, for over an iterable, and itertools.accumulate.

Generators for pipelines: running_total(read_numbers(file)) reads, adds and yields one value at a time, never holding the file in memory. You can chain generators like Unix pipes.

accumulate takes any function: accumulate(numbers, max) gives the running maximum; accumulate(numbers, operator.mul) the running product.

Cost: O(n) time, O(1) memory.

What an interviewer might ask next: Yield the running average instead. (Keep the count too, and yield total / count.)