[Python-checkins] r72813 - python/trunk/Doc/library/collections.rst

raymond.hettinger python-checkins at python.org
Fri May 22 03:06:44 CEST 2009


Author: raymond.hettinger
Date: Fri May 22 03:06:44 2009
New Revision: 72813

Log:
Fix-up moving average example.

Modified:
   python/trunk/Doc/library/collections.rst

Modified: python/trunk/Doc/library/collections.rst
==============================================================================
--- python/trunk/Doc/library/collections.rst	(original)
+++ python/trunk/Doc/library/collections.rst	Fri May 22 03:06:44 2009
@@ -476,16 +476,14 @@
     def moving_average(iterable, n=3):
         # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
         # http://en.wikipedia.org/wiki/Moving_average
-        n = float(n)
         it = iter(iterable)
-        d = deque(itertools.islice(it, n))
+        d = deque(itertools.islice(it, n-1))
+        d.appendleft(0)
         s = sum(d)
-        if len(d) == n:
-            yield s / n
         for elem in it:
             s += elem - d.popleft()
             d.append(elem)
-            yield s / n
+            yield s / float(n)
 
 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


More information about the Python-checkins mailing list