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?
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.
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.
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)}.
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)
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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With