draft of coroutine examples
This commit is contained in:
@@ -45,7 +45,7 @@ Result = collections.namedtuple('Result', 'sum terms average')
|
||||
|
||||
def adder_coro(initial=0):
|
||||
total = initial
|
||||
num_terms = 0
|
||||
count = 0
|
||||
while True:
|
||||
try:
|
||||
term = yield total
|
||||
@@ -54,8 +54,8 @@ def adder_coro(initial=0):
|
||||
if term is None:
|
||||
break
|
||||
total += term
|
||||
num_terms += 1
|
||||
return Result(total, num_terms, total/num_terms)
|
||||
count += 1
|
||||
return Result(total, count, total/count)
|
||||
|
||||
|
||||
def prompt():
|
||||
|
||||
@@ -3,9 +3,13 @@ Closing a generator raises ``GeneratorExit`` at the pending ``yield``
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send(20)
|
||||
30
|
||||
>>> adder.send(30)
|
||||
60
|
||||
>>> adder.close()
|
||||
-> total: 60 terms: 3 average: 20.0
|
||||
|
||||
@@ -14,7 +18,9 @@ Other exceptions propagate to the caller:
|
||||
|
||||
>>> adder = adder_coro()
|
||||
>>> next(adder)
|
||||
0
|
||||
>>> adder.send(10)
|
||||
10
|
||||
>>> adder.send('spam')
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
@@ -25,13 +31,13 @@ Other exceptions propagate to the caller:
|
||||
|
||||
def adder_coro(initial=0):
|
||||
total = initial
|
||||
num_terms = 0
|
||||
count = 0
|
||||
try:
|
||||
while True:
|
||||
term = yield
|
||||
term = yield total
|
||||
total += term
|
||||
num_terms += 1
|
||||
count += 1
|
||||
except GeneratorExit:
|
||||
average = total / num_terms
|
||||
average = total / count
|
||||
msg = '-> total: {} terms: {} average: {}'
|
||||
print(msg.format(total, num_terms, average))
|
||||
print(msg.format(total, count, average))
|
||||
|
||||
Reference in New Issue
Block a user