Fix the Generator Bug
Advanced · Fix the bug · 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 lessonThis generator should count words, yielding the running count after each word is sent. But it has a bug. Fix it.
def word_counter():
count = 0
while True:
word = yield
count += 1
print(f'Word {count}: {word}')Expected output when used:
Word 1: hello
Word 2: world
Word 3: pythondef word_counter():
count = 0
while True:
word = yield
count += 1
print(f'Word {count}: {word}')
wc = word_counter()
# Something is missing here...
wc.send('hello')
wc.send('world')
wc.send('python')
More Generator exercises
- Your First GeneratorIntermediate
- Predict the Generator OutputIntermediate
- Refactor to a GeneratorIntermediate
- Flatten with yield fromAdvanced
- Build a Data PipelineAdvanced
- Infinite Fibonacci GeneratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz