[Python-checkins] cpython (2.7): Add pure python equivalent code for reduce().

raymond.hettinger python-checkins at python.org
Thu Feb 2 09:52:41 CET 2012


http://hg.python.org/cpython/rev/ef770e20c7c3
changeset: 74720:ef770e20c7c3
branch: 2.7
user: Raymond Hettinger <python at rcn.com>
date: Thu Feb 02 00:48:46 2012 -0800
summary:
 Add pure python equivalent code for reduce().
files:
 Doc/library/functions.rst | 12 ++++++++++++
 1 files changed, 12 insertions(+), 0 deletions(-)
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -1058,7 +1058,19 @@
 it is placed before the items of the iterable in the calculation, and serves as
 a default when the iterable is empty. If *initializer* is not given and
 *iterable* contains only one item, the first item is returned.
+ Roughly equivalent to::
 
+ def reduce(function, iterable, initializer=None):
+ it = iter(iterable)
+ if initializer is None:
+ try:
+ initializer = next(it)
+ except StopIteration:
+ raise TypeError('reduce() of empty sequence with no initial value')
+ accum_value = initializer
+ for x in iterable:
+ accum_value = function(accum_value, x)
+ return accum_value
 
 .. function:: reload(module)
 
-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /