Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Power set and Cartesian Product of a set python

I am trying to find the cartesian product of two different sets. I can not find anything on the web about cartesian products of sets it's either of list or dictionaries.

Also power set is very confusing.

Neither one of these are in my book I have been using.

Could one of yall point me to the right direction.

like image 474
bradb Avatar asked Apr 26 '12 23:04

bradb


1 Answers

For the Cartesian product, check out itertools.product.

For the powerset, the itertools docs also give us a recipe:

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))

For example:

>>> test = {1, 2, 3}
>>> list(powerset(test))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(product(test, test))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
like image 180
Gareth Latty Avatar answered Oct 17 '22 21:10

Gareth Latty