Coroutine With Send in Python
Level 5276 keystrokes
This demonstrates a coroutine that receives values via send() and yields running averages.
Python code
# Generator-based coroutine that keeps a running average1def running_average(): # total keeps sum of all values2 total = 0 # count tracks number of values received3 count = 0 # average stores the current running average4 average = None # Infinite loop to keep receiving values5 while True: # yield pauses and returns average, receives new value6 value = yield average # Only process if value was sent (not None)7 if value is not None: # Add value to running total8 total += value # Increment count9 count += 1 # Calculate new average10 average = total / count11 # Create the coroutine object12coro = running_average()# Prime the coroutine by advancing to first yield13next(coro)# Send 10, get average 10.014print(coro.send(10))# Send 20, get average 15.015print(coro.send(20))# Send 30, get average 20.016print(coro.send(30))# Clean up by closing the coroutine17coro.close()Output
10.0 15.0 20.0
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 10)× 10=× 8.× 4:× 3_× 2+× 2/× 1