[Python-checkins] r65128 - in python/trunk: Doc/library/itertools.rst Lib/test/test_itertools.py
raymond.hettinger
python-checkins at python.org
Sat Jul 19 02:43:01 CEST 2008
Author: raymond.hettinger
Date: Sat Jul 19 02:43:00 2008
New Revision: 65128
Log:
Add recipe to the itertools docs.
Modified:
python/trunk/Doc/library/itertools.rst
python/trunk/Lib/test/test_itertools.py
Modified: python/trunk/Doc/library/itertools.rst
==============================================================================
--- python/trunk/Doc/library/itertools.rst (original)
+++ python/trunk/Doc/library/itertools.rst Sat Jul 19 02:43:00 2008
@@ -701,3 +701,18 @@
for d, s in izip(data, selectors):
if s:
yield d
+
+ def combinations_with_replacement(iterable, r):
+ "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC"
+ pool = tuple(iterable)
+ n = len(pool)
+ indices = [0] * r
+ yield tuple(pool[i] for i in indices)
+ while 1:
+ for i in reversed(range(r)):
+ if indices[i] != n - 1:
+ break
+ else:
+ return
+ indices[i:] = [indices[i] + 1] * (r - i)
+ yield tuple(pool[i] for i in indices)
Modified: python/trunk/Lib/test/test_itertools.py
==============================================================================
--- python/trunk/Lib/test/test_itertools.py (original)
+++ python/trunk/Lib/test/test_itertools.py Sat Jul 19 02:43:00 2008
@@ -1285,6 +1285,21 @@
... if s:
... yield d
+>>> def combinations_with_replacement(iterable, r):
+... "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC"
+... pool = tuple(iterable)
+... n = len(pool)
+... indices = [0] * r
+... yield tuple(pool[i] for i in indices)
+... while 1:
+... for i in reversed(range(r)):
+... if indices[i] != n - 1:
+... break
+... else:
+... return
+... indices[i:] = [indices[i] + 1] * (r - i)
+... yield tuple(pool[i] for i in indices)
+
This is not part of the examples but it tests to make sure the definitions
perform as purported.
@@ -1362,6 +1377,9 @@
>>> list(compress('abcdef', [1,0,1,0,1,1]))
['a', 'c', 'e', 'f']
+>>> list(combinations_with_replacement('abc', 2))
+[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
+
"""
__test__ = {'libreftest' : libreftest}
More information about the Python-checkins
mailing list