Created
April 1, 2017 07:38
-
-
Save tkf/d43a8f53cf9a2edccfc86c79572fb8de to your computer and use it in GitHub Desktop.
Online average using coroutine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import itertools | |
def coroutine_send(func): | |
@functools.wraps(func) | |
def start(*args, **kwds): | |
cr = func(*args, **kwds) | |
next(cr) | |
return cr.send | |
return start | |
@coroutine_send | |
def online_average(): | |
""" | |
Online average calculator. | |
>>> avgr = online_average() | |
>>> for i in range(3): | |
... a = avgr(i) | |
... print(a) | |
... | |
0 | |
0.5 | |
1.0 | |
>>> a == sum(range(3)) / 3 | |
True | |
""" | |
s = yield | |
for n in itertools.count(2): | |
s = (yield s) / n + s * (n - 1) / n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment