Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ace6733

Browse files
committed
Backport r68942: update powerset() recipe.
1 parent 89e1296 commit ace6733

2 files changed

Lines changed: 8 additions & 12 deletions

File tree

Doc/library/itertools.rst

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -590,11 +590,9 @@ which incur interpreter overhead.
590590
nexts = cycle(islice(nexts, pending))
591591
592592
def powerset(iterable):
593-
"powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])"
594-
# Recipe credited to Eric Raymond
595-
pairs = [(2**i, x) for i, x in enumerate(iterable)]
596-
for n in xrange(2**len(pairs)):
597-
yield set(x for m, x in pairs if m&n)
593+
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
594+
s = list(iterable)
595+
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
598596

599597
def compress(data, selectors):
600598
"compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"

Lib/test/test_itertools.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1277,11 +1277,9 @@ def __init__(self, newarg=None, *args):
12771277
... nexts = cycle(islice(nexts, pending))
12781278
12791279
>>> def powerset(iterable):
1280-
... "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])"
1281-
... # Recipe credited to Eric Raymond
1282-
... pairs = [(2**i, x) for i, x in enumerate(iterable)]
1283-
... for n in range(2**len(pairs)):
1284-
... yield set(x for m, x in pairs if m&n)
1280+
... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1281+
... s = list(iterable)
1282+
... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
12851283
12861284
>>> def compress(data, selectors):
12871285
... "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
@@ -1379,8 +1377,8 @@ def __init__(self, newarg=None, *args):
13791377
>>> list(roundrobin('abc', 'd', 'ef'))
13801378
['a', 'd', 'e', 'b', 'f', 'c']
13811379
1382-
>>> list(map(sorted, powerset('ab')))
1383-
[[], ['a'], ['b'], ['a', 'b']]
1380+
>>> list(powerset([1,2,3]))
1381+
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
13841382
13851383
>>> list(compress('abcdef', [1,0,1,0,1,1]))
13861384
['a', 'c', 'e', 'f']

0 commit comments

Comments
 (0)