Kaydet (Commit) 33691670 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Add recipe to the itertools docs.

üst 3c212163
...@@ -701,3 +701,18 @@ which incur interpreter overhead. ...@@ -701,3 +701,18 @@ which incur interpreter overhead.
for d, s in izip(data, selectors): for d, s in izip(data, selectors):
if s: if s:
yield d 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)
...@@ -1285,6 +1285,21 @@ Samuele ...@@ -1285,6 +1285,21 @@ Samuele
... if s: ... if s:
... yield d ... 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 This is not part of the examples but it tests to make sure the definitions
perform as purported. perform as purported.
...@@ -1362,6 +1377,9 @@ False ...@@ -1362,6 +1377,9 @@ False
>>> list(compress('abcdef', [1,0,1,0,1,1])) >>> list(compress('abcdef', [1,0,1,0,1,1]))
['a', 'c', 'e', 'f'] ['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} __test__ = {'libreftest' : libreftest}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment