Running total

EasyIterator & Generator Programs · 13 of 20

Write a generator that yields the running total of a list.

Advertisement
Output
[5, 8, 16, 18] [5, 8, 16, 18]

Approach

  1. Keep a total and yield after each addition; compare with itertools.accumulate.

Solution

Python
from itertools import accumulate def running_total(numbers):    total = 0    for n in numbers:        total += n        yield total print(list(running_total([5, 3, 8, 2])), list(accumulate([5, 3, 8, 2])))
Output
[5, 8, 16, 18] [5, 8, 16, 18]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment