9

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
bradb
  • 129
  • 1
  • 2
  • 8

1 Answers1

18

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)]
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • thank you for the edit it made it a lot more clear I am trying to implement these into my code currently do i need to import itertools ? Thanks Again! – bradb Apr 26 '12 at 23:56
  • Yes, you need to import the functions you use from ``itertools``, as with any functions you use from another module. – Gareth Latty Apr 26 '12 at 23:58
  • powerset might be better defined with `s = set(iterable)`. – Casey Kuball Apr 26 '12 at 23:59
  • @Darthfett: That would make it a less general solution. But yes, if you are working purely with sets, that would work. – Gareth Latty Apr 27 '12 at 00:01