]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Improved itertools recipe for generating powerset().
authorRaymond Hettinger <python@rcn.com>
Sun, 25 Jan 2009 21:31:47 +0000 (21:31 +0000)
committerRaymond Hettinger <python@rcn.com>
Sun, 25 Jan 2009 21:31:47 +0000 (21:31 +0000)
Doc/library/itertools.rst
Lib/test/test_itertools.py

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