[Python-checkins] cpython: Add another example for accumulate().

raymond.hettinger python-checkins at python.org
Thu Apr 21 20:09:38 CEST 2011


http://hg.python.org/cpython/rev/e8d8c735f3e2
changeset:   69515:e8d8c735f3e2
user:        Raymond Hettinger <python at rcn.com>
date:        Thu Apr 21 11:09:28 2011 -0700
summary:
  Add another example for accumulate().

files:
  Doc/library/itertools.rst |  21 ++++++++++++++++++---
  1 files changed, 18 insertions(+), 3 deletions(-)


diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -104,9 +104,13 @@
                 total = func(total, element)
                 yield total
 
-    Uses for the *func* argument include :func:`min` for a running minimum,
-    :func:`max` for a running maximum, and :func:`operator.mul` for a running
-    product::
+    There are a number of uses for the *func* argument.  It can be set to
+    :func:`min` for a running minimum, :func:`max` for a running maximum, or
+    :func:`operator.mul` for a running product.  Amortization tables can be
+    built by accumulating interest and applying payments.  First-order
+    `recurrence relations <http://en.wikipedia.org/wiki/Recurrence_relation>`_
+    can be modeled by supplying the initial value in the iterable and using only
+    the accumulated total in *func* argument::
 
       >>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
       >>> list(accumulate(data, operator.mul))     # running product
@@ -119,6 +123,17 @@
       >>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
       [1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
 
+      # Chaotic recurrence relation http://en.wikipedia.org/wiki/Logistic_map
+      >>> logistic_map = lambda x, _:  r * x * (1 - x)
+      >>> r = 3.8
+      >>> x0 = 0.4
+      >>> inputs = repeat(x0, 36)     # only the initial value is used
+      >>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)]
+      ['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
+       '0.88' ,'0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
+       '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
+       '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']
+
     .. versionadded:: 3.2
 
     .. versionchanged:: 3.3

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list