]> granicus.if.org Git - python/commitdiff
Add recipe to the itertools docs.
authorRaymond Hettinger <python@rcn.com>
Sat, 19 Jul 2008 00:43:00 +0000 (00:43 +0000)
committerRaymond Hettinger <python@rcn.com>
Sat, 19 Jul 2008 00:43:00 +0000 (00:43 +0000)
Doc/library/itertools.rst
Lib/test/test_itertools.py

index 81b2c7fed5d56df5e146ac615dedc5651e4222cf..9a3626f98cd4ffc68e371d09a366e422c74a2b79 100644 (file)
@@ -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)
index 98cceb7f09eda0f1cad19a4cec7cf672c73d528b..82e1ee43e8e3af108e777728b87760595109904f 100644 (file)
@@ -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}