Skip to content

Instantly share code, notes, and snippets.

@tkf
Created April 1, 2017 07:38
Show Gist options
  • Save tkf/d43a8f53cf9a2edccfc86c79572fb8de to your computer and use it in GitHub Desktop.
Save tkf/d43a8f53cf9a2edccfc86c79572fb8de to your computer and use it in GitHub Desktop.
Online average using coroutine
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