Fix-up moving average example.

This commit is contained in:
Raymond Hettinger 2009-05-22 01:06:44 +00:00
parent a50af06931
commit 9b6f13ee82
1 changed files with 3 additions and 5 deletions

View File

@ -476,16 +476,14 @@ added elements by appending to the right and popping to the left::
def moving_average(iterable, n=3): def moving_average(iterable, n=3):
# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
# http://en.wikipedia.org/wiki/Moving_average # http://en.wikipedia.org/wiki/Moving_average
n = float(n)
it = iter(iterable) it = iter(iterable)
d = deque(itertools.islice(it, n)) d = deque(itertools.islice(it, n-1))
d.appendleft(0)
s = sum(d) s = sum(d)
if len(d) == n:
yield s / n
for elem in it: for elem in it:
s += elem - d.popleft() s += elem - d.popleft()
d.append(elem) d.append(elem)
yield s / n yield s / float(n)
The :meth:`rotate` method provides a way to implement :class:`deque` slicing and The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
deletion. For example, a pure python implementation of ``del d[n]`` relies on deletion. For example, a pure python implementation of ``del d[n]`` relies on