...
/Solution Review: Coroutine to Compute Running Maximum
Solution Review: Coroutine to Compute Running Maximum
The solution to the 'Coroutine to Compute Running Maximum' challenge.
We'll cover the following...
import mathdef maximum():result = - math.infwhile True:value = yield result # Recieving valuesif value > result: # Deciding on maximumresult = valuecoroutine = maximum()next(coroutine)# Sending valuesprint(coroutine.send(1))print(coroutine.send(7))print(coroutine.send(3))print(coroutine.send(10))print(coroutine.send(5))print(coroutine.send(8))print(coroutine.send(12))coroutine.close() # Closing coroutine
Explanation
Look at line 4. We declare result to store the maximum of the values received from multiple invocations.
Note:
-math.infis known as the negative infinity in Python. We setresultto-math.infas all integers are greater than-math.inf.
Then, we set an infinite while loop. Every value received by the caller is yielded and stored in the local variable: value. If value is greater than result, the result is updated. How simple is that!
Then we make an object coroutine, and activate it with next() which suspends the coroutine for the first time. Then we send around seven different values (from line 16 to line 22), and we get the maximum of the values after every suspension.
To stop the coroutine, we explicitly call close() at line 24.