mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
Backport r68942: update powerset() recipe.
This commit is contained in:
parent
a96f9f6732
commit
5cd012b64e
2 changed files with 8 additions and 12 deletions
|
@ -673,11 +673,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 compress(data, selectors):
|
def compress(data, selectors):
|
||||||
"compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
|
"compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
|
||||||
|
|
|
@ -1256,11 +1256,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 compress(data, selectors):
|
>>> def compress(data, selectors):
|
||||||
... "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
|
... "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
|
||||||
|
@ -1358,8 +1356,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(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']
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue