1

Assume that we have n lists in python like A1,A2,...,An. We name A*={x1,x2,...,xn} a combination of these lists if x1 is in A1, x2 is in A2,..., xn is in An. By mathematics, we know that the number of these combinations is |A1| * |A2|*... * |An|. How can I code a function in python to do this for me and return all these combinations?

ksohan
  • 1,165
  • 2
  • 9
  • 23
K.N
  • 871
  • 2
  • 10
  • 30

1 Answers1

1

You can use itertools.product:

from itertools import product

a1 = range(0, 3)
a2 = range(3, 6)
a3 = range(6, 9)

print(list(product(a1, a2, a3)))

Output:

[(0, 3, 6), (0, 3, 7), (0, 3, 8), (0, 4, 6), (0, 4, 7), (0, 4, 8), (0, 5, 6), (0, 5, 7), (0, 5, 8), (1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 5, 6), (1, 5, 7), (1, 5, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 5, 6), (2, 5, 7), (2, 5, 8)]
iz_
  • 15,923
  • 3
  • 25
  • 40