Running Total
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?
- It must read the whole input before the first output
- It can output the first total as soon as it has read the first number
- 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.)
VISIBLE = 3
CASES = [
('result = list(running_total([1, 2, 3, 4]))', [1, 3, 6, 10], 'a list'),
('result = list(running_total([5, -2, 4]))', [5, 3, 7], 'negative numbers'),
('result = list(running_total([]))', [], 'nothing to add'),
('result = list(running_total(iter([1, 1, 1])))', [1, 2, 3], 'an iterator'),
('result = list(running_total(range(1, 6)))', [1, 3, 6, 10, 15], 'a range'),
('consumed = []\ndef source():\n for i in range(1, 6):\n consumed.append(i)\n yield i\ng = running_total(source())\nnext(g)\nnext(g)\nresult = len(consumed)', 2, 'it is lazy'),
('result = list(running_total([0.5, 0.25]))', [0.5, 0.75], 'decimals'),
('result = list(running_total([7]))', [7], 'one number'),
]