[Python-checkins] r68942 - in python/trunk: Doc/library/itertools.rst Lib/test/test_itertools.py

raymond.hettinger python-checkins at python.org
Sun Jan 25 22:31:47 CET 2009


Author: raymond.hettinger
Date: Sun Jan 25 22:31:47 2009
New Revision: 68942
Log:
Improved itertools recipe for generating powerset().
Modified:
 python/trunk/Doc/library/itertools.rst
 python/trunk/Lib/test/test_itertools.py
Modified: python/trunk/Doc/library/itertools.rst
==============================================================================
--- python/trunk/Doc/library/itertools.rst	(original)
+++ python/trunk/Doc/library/itertools.rst	Sun Jan 25 22:31:47 2009
@@ -687,11 +687,9 @@
 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"
Modified: python/trunk/Lib/test/test_itertools.py
==============================================================================
--- python/trunk/Lib/test/test_itertools.py	(original)
+++ python/trunk/Lib/test/test_itertools.py	Sun Jan 25 22:31:47 2009
@@ -1287,11 +1287,9 @@
 ... 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 @@
 >>> 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')]


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /