Commit 68d919e4 authored by Raymond Hettinger's avatar Raymond Hettinger

Improved itertools recipe for generating powerset().

parent 2bcb8e9b
...@@ -687,11 +687,9 @@ which incur interpreter overhead. ...@@ -687,11 +687,9 @@ which incur interpreter overhead.
nexts = cycle(islice(nexts, pending)) nexts = cycle(islice(nexts, pending))
def powerset(iterable): def powerset(iterable):
"powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
# Recipe credited to Eric Raymond s = list(iterable)
pairs = [(2**i, x) for i, x in enumerate(iterable)] return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
for n in xrange(2**len(pairs)):
yield set(x for m, x in pairs if m&n)
def combinations_with_replacement(iterable, r): def combinations_with_replacement(iterable, r):
"combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
......
...@@ -1287,11 +1287,9 @@ Samuele ...@@ -1287,11 +1287,9 @@ Samuele
... nexts = cycle(islice(nexts, pending)) ... nexts = cycle(islice(nexts, pending))
>>> def powerset(iterable): >>> def powerset(iterable):
... "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" ... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
... # Recipe credited to Eric Raymond ... s = list(iterable)
... pairs = [(2**i, x) for i, x in enumerate(iterable)] ... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
... for n in xrange(2**len(pairs)):
... yield set(x for m, x in pairs if m&n)
>>> def combinations_with_replacement(iterable, r): >>> def combinations_with_replacement(iterable, r):
... "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC" ... "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC"
...@@ -1385,8 +1383,8 @@ perform as purported. ...@@ -1385,8 +1383,8 @@ perform as purported.
>>> list(roundrobin('abc', 'd', 'ef')) >>> list(roundrobin('abc', 'd', 'ef'))
['a', 'd', 'e', 'b', 'f', 'c'] ['a', 'd', 'e', 'b', 'f', 'c']
>>> map(sorted, powerset('ab')) >>> list(powerset([1,2,3]))
[[], ['a'], ['b'], ['a', 'b']] [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(combinations_with_replacement('abc', 2)) >>> list(combinations_with_replacement('abc', 2))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')] [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
......
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