pythonadvanced10 minutes
Predict the Output of Nested Generator and Coroutine Logic in Python
Analyze a complex Python function that uses nested generators, coroutines, and yield expressions to predict its output. This challenge tests your understanding of Python's generator mechanics and flow control.
Challenge prompt
Consider the following Python code snippet involving nested generators and the send() method on coroutines. Predict the exact sequence of printed output when the code is executed. Do not run the code; rely on logic and deep understanding of generator flow control and interaction. Explain your reasoning in comments.
Guidance
- • Focus on how send() affects the yield expressions and how values are passed between generators.
- • Pay attention to the order of generator activation and suspension points.
- • Remember that a generator's yield expression both outputs a value and receives a value via send().
Hints
- • Trace the code line-by-line, simulating the generator states manually.
- • Keep track of what each yield expression returns and what values are sent back to them.
- • Note when the control switches between gen1 and gen2 and how their outputs interleave.
Starter code
def gen2():
val = yield 'Start gen2'
val2 = yield val + 5
yield val2 * 2
def gen1():
g = gen2()
x = yield next(g)
y = yield g.send(x + 1)
yield g.send(y + 2)
runner = gen1()
print(next(runner)) # prime gen1
print(runner.send(3)) # send 3 into gen1
print(runner.send(4)) # send 4 into gen1
print(next(runner)) # final outputExpected output
'Start gen2' 9 12 12
Core concepts
generatorscoroutinesyield and sendflow control
Challenge a Friend
Send this duel to someone else and see if they can solve it.