Applications of Cartesian Product

Applications of Cartesian Product

·

2 min read

Sometimes we need to determine every combination of sets of items. This cross/unrestricted-join is known as a Cartesian or cross product. For example, determin all combinations of drink sizes, add-ons, and coffee type from a Starbucks.

sizes = ['Short', 'Tall', 'Grande', 'Venti', 'Trenta']
drinks = ['Coffee', 'Hot Chocolate', 'Americano', 'Cappuccino', 'Latte', 'Macchiato', 'Mocha']
add_ons = ['Milk', 'Cream', 'Foam', 'Cinnamon' 'Syrup']


all_drink_combos = []
for s in sizes:
  for d in drinks:
    for a in add_ons:
        all_drink_combos.append((s, d, a))


print(all_drink_combos)

I won't print out the 175 elements (5 x 7 x 5):

[('Short', 'Coffee', 'Milk'), ('Short', 'Coffee', 'Cream') ... ('Trenta', 'Mocha', 'Cinnamon'), ('Trenta', 'Mocha', 'Syrup'))]

We can also achieve this by using itertools.product:

all_drink_combos = itertools.product(sizes, drinks, add_ons)

If we wanted to provide all possible chessboard cells using Algebraic Notation and list comprehension:

file, rank = "abcdefgh", "01234567"
cells = [f + r for f in files for r in ranks]
print(cells)
['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8']

References