# Teaching Kids Programming – Introduction to Cartesian Product (Math)

Teaching Kids Programming – Introduction to Cartesian Product (Math) | ninjasquad

Teaching Kids Programming: Videos on Data Structures and Algorithms

Cartesian Product is a math operation that is applied on two or more sets. It is:

$tex_dee9f90294bfd8ea4e25eea3986bc4ca Teaching Kids Programming - Introduction to Cartesian Product (Math) math python teaching kids programming youtube video$ where A and B are sets.

For example:

A = {1, 2}, B = {3, 4} and the Cartesian Product of A and B noted as A x B is {{1, 3}, {1, 4}, {2, 3}, {2, 4}}.

The Cardinality (the number of the elements in the set) for the Cartesian Product can be computed as:

$tex_cdadc5b00b6398b2a069878ccecb20cc Teaching Kids Programming - Introduction to Cartesian Product (Math) math python teaching kids programming youtube video$

As for each element in set A, we pair it with each element in set B.

Cartesian Product can be applied to multiple sets:

And the Cardinality is the product of the sizes of all sets:

$tex_6357d5a392d0321d4b17d3077b262604 Teaching Kids Programming - Introduction to Cartesian Product (Math) math python teaching kids programming youtube video$

Clearly, the commutative rule does not stand:

$tex_7d73464e3209f59608cf04e95e210182 Teaching Kids Programming - Introduction to Cartesian Product (Math) math python teaching kids programming youtube video$

except when B is empty e.g. $tex_c72f0ddf33d9bacba2d8144196a5bd1d Teaching Kids Programming - Introduction to Cartesian Product (Math) math python teaching kids programming youtube video$

### Cartesian Product in Python

We can import the product function from itertools package:

 ```1 ``` `from itertools import product`
`from itertools import product`

The product method returns an iterator – and we can convert it to list:

 ```1 2 3 4 ``` ```A = (1, 2) B = (3, 4) C = list(product(A, B)) # C = [(1, 3), (1, 4), (2, 3), (2, 4)]```
```A = (1, 2)
B = (3, 4)
C = list(product(A, B))
# C = [(1, 3), (1, 4), (2, 3), (2, 4)]```

The product function can be specified the repeat parameter:

 ```1 2 ``` ```for k, i, j in product(range(n), repeat=3):     pass```
```for k, i, j in product(range(n), repeat=3):
pass```

This is the same as the following O(N^3) loops:

 ```1 2 3 4 ``` ```for k in range(n):     for i in range(n):         for j in range(n):             pass```
```for k in range(n):
for i in range(n):
for j in range(n):
pass```

GD Star Rating