summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2008-07-19 00:43:00 (GMT)
committerRaymond Hettinger <python@rcn.com>2008-07-19 00:43:00 (GMT)
commit3369167089cb2390b16ced87a0c54a3678342e83 (patch)
treefa1f8dec0ec490803e5a4f4c5020871ca25c6f51
parent3c212163ec5fadeabf4070c2b2e22bd85e2d2aa0 (diff)
downloadcpython-3369167089cb2390b16ced87a0c54a3678342e83.zip
cpython-3369167089cb2390b16ced87a0c54a3678342e83.tar.gz
cpython-3369167089cb2390b16ced87a0c54a3678342e83.tar.bz2
Add recipe to the itertools docs.
-rw-r--r--Doc/library/itertools.rst15
-rw-r--r--Lib/test/test_itertools.py18
2 files changed, 33 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 81b2c7f..9a3626f 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -701,3 +701,18 @@ which incur interpreter overhead.
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)
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 98cceb7..82e1ee4 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -1285,6 +1285,21 @@ Samuele
... 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 @@ False
>>> 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}