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 lessonWrite 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.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected 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
- Your First GeneratorIntermediate
- Predict the Generator OutputIntermediate
- Refactor to a GeneratorIntermediate
- Flatten with yield fromAdvanced
- Build a Data PipelineAdvanced
- Fix the Generator BugAdvanced
- Infinite Fibonacci GeneratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz