tags:

views:

70

answers:

4

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?

+1  A: 

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)])
Eugene
+5  A: 

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)
Mark Byers
+1  A: 

Mark, good idea.

>>> def set_product(the_set, n):
    return set(itertools.product(the_set, repeat=n))

>>> s2 = set((0,1,2))
>>> set_product(s2, 3)
set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])

You could also extend the set type and make the __pow__ method do this.

Eugene
A: 
print 'You can do like this with generator:'
print set((a,b,c) for a in s1 for b in s1 for c in s1)
Tony Veijalainen