Skip to content

Commit 654241b

Browse files
committed
Add running_mean recipe to demonstrate accumulate and count
1 parent e423e0c commit 654241b

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

Doc/library/itertools.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -845,7 +845,7 @@ and :term:`generators <generator>` which incur interpreter overhead.
845845
from contextlib import suppress
846846
from functools import reduce
847847
from math import comb, isqrt, prod, sumprod
848-
from operator import getitem, is_not, itemgetter, mul, neg
848+
from operator import getitem, is_not, itemgetter, mul, neg, truediv
849849

850850
# ==== Basic one liners ====
851851

@@ -862,6 +862,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
862862
"Return function(0), function(1), ..."
863863
return map(function, count(start))
864864

865+
def running_mean(iterable):
866+
"Yield the cumulative arithmetic mean."
867+
# running_mean([8.5, 9.5, 7.5, 7.0]) -> 8.5 9.0 8.5 8.0
868+
return map(truediv, accumulate(iterable), count(1))
869+
865870
def repeatfunc(function, times=None, *args):
866871
"Repeat calls to a function with specified arguments."
867872
if times is None:
@@ -1234,6 +1239,10 @@ and :term:`generators <generator>` which incur interpreter overhead.
12341239
[0, 2, 4, 6]
12351240

12361241

1242+
>>> list(running_median([8.5, 9.5, 7.5, 7.0]))
1243+
[8.5, 9.0, 8.5, 8.0]
1244+
1245+
12371246
>>> for _ in loops(5):
12381247
... print('hi')
12391248
...

0 commit comments

Comments
 (0)