Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: powerset of a given set with generators [duplicate]

I am trying to build a list of subsets of a given set in Python with generators. Say I have

set([1, 2, 3])

as input, I should have

[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]

as output. How can I achieve this?

like image 468
linkyndy Avatar asked Sep 16 '13 11:09

linkyndy


People also ask

How do you define a power set in Python?

Power Set: Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}. Method 1: For a given set[] S, the power set can be found by generating all binary numbers between 0 and 2n-1, where n is the size of the set.


1 Answers

The fastest way is by using itertools, especially chain and combinations:

>>> from itertools import chain, combinations
>>> i = set([1, 2, 3])
>>> for z in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
    print z 
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
>>> 

If you need a generator just use yield and turn tuples into sets:

def powerset_generator(i):
    for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
        yield set(subset)

and then simply:

>>> for i in powerset_generator(i):
    print i


set([])
set([1])
set([2])
set([3])
set([1, 2])
set([1, 3])
set([2, 3])
set([1, 2, 3])
>>> 
like image 132
Pawel Miech Avatar answered Sep 27 '22 22:09

Pawel Miech