Reputation: 14970
I am trying to understand coroutines
in python with yield
operator.
def minimize():
current = yield
while True:
value = yield current
current = min(value, current)
I have the function minimize()
which returns the minimum value of the all the values that has been sent to the function till that point.
it = minimize()
next(it)
print(it.send(10))
print(it.send(4))
print(it.send(22))
print(it.send(-1))
>>>
10
4
4
-1
I have a question regarding the function.
what does current = yeild
achieve. From what I understood of yield
in a generator context, yeild
returns the next value when you use next()
on the generator object.
Upvotes: 0
Views: 120
Reputation: 30258
Let's follow the flow control, indented items are the minimize()
generator:
it = minimize() # Creates generator
next(it)
current = yield # suspends on yield (implicit None)
print(it.send(10))
current = 10 # resumes
while True:
value = yield 10 # suspends on yield
# Output: 10
print(it.send(4))
value = 4 # resumes
current = min(4, 10)
while True:
current = yield 4
# Output: 4
print(it.send(22))
value = 22
current = min(22, 4)
while True:
current = yield 4
# Output: 4
print(it.send(-1))
value = -1
current = min(-1, 4)
while True:
current = yield -1
# Output: -1
Upvotes: 2