Iterators and generatorsgenerators-running-total
LessonΒ·difficulty 3/5Β·~14 min
Generators: running totals
Generators: running totals
A generator is a function that uses yield instead of return. Each
yield hands back one value and pauses, resuming where it left off when asked
for the next one:
python
def count_up(n):
for i in range(n):
yield i
list(count_up(3)) # [0, 1, 2] β wrap in list() to pull every value out
This lets you produce a sequence lazily, one item at a time, while keeping state (like a running tally) between yields.
Your task
Write a generator running_totals(nums) that yields the cumulative sum
after each element.
python
list(running_totals([1, 2, 3])) # [1, 3, 6]
list(running_totals([])) # []
list(running_totals([5, -5, 5])) # [5, 0, 5]
Hint: keep a total variable starting at 0; in a loop, add each number to it
and yield total.
Tests
- basic sequence
- empty input
- cancels out
- single element
- all zeros (hidden)
- yields lazily (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.