Editor

Runs of Equal Values

Advanced · Stretch · from Python Generators: Process Millions of Items Without Running Out of Memory

From the lesson: Can You Communicate with a Running Generator?

Generators aren't just one-way streets. You can send values back into a paused generator, throw exceptions into it, or close it early.

Read this part of the lesson

Write a generator function runs(iterable) that yields a tuple (value, count) for each run of equal values that follow each other.

list(runs("aaabcc"))       # [('a', 3), ('b', 1), ('c', 2)]
list(runs([1, 1, 2, 1]))   # [(1, 2), (2, 1), (1, 1)]

The input can be any iterable, including another generator reading a huge file or a stream that never ends. So runs() must not read ahead: it yields each run as soon as the next, different value arrives, and never loads the whole input. Some of the tests are hidden.

def runs(iterable):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
list(runs("aaabcc"))[('a', 3), ('b', 1), ('c', 2)]
list(runs([1, 1, 2, 1]))[(1, 2), (2, 1), (1, 1)]

More Generator exercises

All Python exercises · 50 practice problems · Advanced Python quiz