Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set products in Python

Tags:

python

math

A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3­-bit sequences:

{0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}

What's the simplest way to replicate this idea in Python?

like image 386
Eugene Avatar asked Jul 17 '10 14:07

Eugene


People also ask

What is product () in Python?

product() is a part of a python module itertools; a collection of tools used to handle iterators. Together all these tools form iterator algebra. Itertools will make your code stand out. Above all, it will make it more pythonic.

How do you use set items in Python?

You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

What is a cartesian product Python?

The cartesian product (or cross product) of A and B, denoted by A x B, is the set A x B = {(a,b) | a ∈ A and b ∈ B}. The elements (a,b) are ordered pairs. For example if A = {1,2} and B = {4,5,6} then the cartesian products of A and B is AxB = {(1,4),(1,5),(1,6),(2,4),(2,5),(2,6)}.


2 Answers

In Python 2.6 or newer you can use itertools.product with the optional argument repeat:

>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))

For older versions of Python you can implement product using the code found in the documentation:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
like image 153
Mark Byers Avatar answered Sep 19 '22 23:09

Mark Byers


I suppose this works?

>>> s1 = set((0,1))
>>> set(itertools.product(s1,s1,s1))
set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])
like image 22
Eugene Avatar answered Sep 22 '22 23:09

Eugene