Search code examples
pythonradix

How to generate all possible combinations of N slots with V possible values?


I have N ordered slots. Each slot has a value within V possible values

N = 4 # number of objects (e.g. slots)
possible_values = ['A','B']
V = len(possible_values )

How would it be possible to generate the list of all possible combinations in Python? For instance, when V=2 and N=4, I would like to get the following list of the 2**4 different combinations:

combinations = [
    [ 'A', 'A', 'A', 'A' ], # combination 0
    [ 'A', 'A', 'A', 'B' ], # combination 1
    [ 'A', 'A', 'B', 'A' ], # combination 2
    [ 'A', 'A', 'B', 'B' ], # combination 3
    [ 'A', 'B', 'A', 'A' ], # combination 4
    [ 'A', 'B', 'A', 'B' ], # combination 5
    [ 'A', 'B', 'B', 'A' ], # combination 6
    [ 'A', 'B', 'B', 'B' ], # combination 7
    [ 'B', 'A', 'A', 'A' ], # combination 8
    [ 'B', 'A', 'A', 'B' ], # combination 9
    [ 'B', 'A', 'B', 'A' ], # combination 10
    [ 'B', 'A', 'B', 'B' ], # combination 11
    [ 'B', 'B', 'A', 'A' ], # combination 12
    [ 'B', 'B', 'A', 'B' ], # combination 13
    [ 'B', 'B', 'B', 'A' ], # combination 14
    [ 'B', 'B', 'B', 'B' ], # combination 15
]

I would like the code to work when N and V vary. For example, when N=9 slots and V=4 possible values, I expect the list of the 4**9=262144 possible combinations.


Solution

  • N = 4 # number of objects (e.g. slots)
    possible_values = ['A','B']
    
    result = itertools.product(possible_values, repeat=N)
    
    print(list(result))