updated from atlas

This commit is contained in:
Luciano Ramalho
2015-02-20 14:33:00 -02:00
parent e910ec5458
commit 304d628066
4 changed files with 56 additions and 25 deletions

View File

@@ -1,31 +1,61 @@
"""
A coroutine to compute a running average
A coroutine to compute a running average.
>>> coro_avg = averager() # <1>
>>> from inspect import getgeneratorstate
>>> getgeneratorstate(coro_avg) # <2>
'GEN_SUSPENDED'
>>> coro_avg.send(10) # <3>
10.0
Testing ``averager`` by itself::
# BEGIN RETURNING_AVERAGER_DEMO1
>>> coro_avg = averager()
>>> next(coro_avg) # <1>
>>> coro_avg.send(10)
>>> coro_avg.send(30)
20.0
>>> coro_avg.send(5)
15.0
>>> coro_avg.send(6.5)
>>> coro_avg.send(None) # <2>
Traceback (most recent call last):
...
StopIteration: Result(count=3, average=15.5)
# END RETURNING_AVERAGER_DEMO1
Catching `StopIteration` to extract the value returned by
the coroutine::
# BEGIN RETURNING_AVERAGER_DEMO2
>>> coro_avg = averager()
>>> next(coro_avg)
>>> coro_avg.send(10)
>>> coro_avg.send(30)
>>> coro_avg.send(6.5)
>>> try:
... coro_avg.send(None)
... except StopIteration as exc:
... result = exc.value
...
>>> result
Result(count=3, average=15.5)
# END RETURNING_AVERAGER_DEMO2
"""
# BEGIN RETURNING_AVERAGER
from collections import namedtuple
Result = namedtuple('Result', 'count total average')
Result = namedtuple('Result', 'count average')
def averager(): # <6>
total = average = 0.0
def averager():
total = 0.0
count = 0
try:
while True:
term = yield average
total += term
count += 1
average = total/count
finally:
return Result(count, total, average)
average = None
while True:
term = yield
if term is None:
break # <1>
total += term
count += 1
average = total/count
return Result(count, average) # <2>
# END RETURNING_AVERAGER