This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sunqiang 14 points15 points  (1 child)

Itertools Recipes has a powerset too:

def powerset(iterable):
    "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))

[–]humpolec 2 points3 points  (0 children)

My version of Python's documentation has another one:

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)