...

/

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...
Press + to interact
Python 3.10.4
import math
def maximum():
result = - math.inf
while True:
value = yield result # Recieving values
if value > result: # Deciding on maximum
result = value
coroutine = maximum()
next(coroutine)
# Sending values
print(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.inf is known as the negative infinity in Python. We set result to -math.inf as 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.


Ask