pythonlistmathcombinations

Python generate all possible combinations of matrix


I need to generate all combinations of a matrix in Python. The input will be two integers n and m, and I need to generate all possible states of that matrix with 1 and 0 as possible values.

For example:

n = 3 m = 2
[[0 0 0] [1 0 0] [1 1 0]
 [0 0 0] [0 0 0] [0 0 0]
 [0 0 0],[0 0 0],[0 0 0] . . . . .
]

Is there a clean and efficient way to do this given I will not know the values for n and m until runtime? The highest value used will be n = 16 m = 16.


Solution

  • One way is by generating all binary sequences of length m*n in a list comprehension, and reshaping them into a (m,n) shaped nested list on each iteration.

    A simple way to generate all sequences is by taking the cartesian product of 01 with n*m repeats, which will be produce 2^(m*n) combinations:

    from itertools import product
    m=3
    n=3
    
    x = [[list(i[x:x+m]) for x in range(0, len(i), m)] for i in product("01", repeat=m*n)]
    

    Output

    [[['0' '0' '0']
      ['0' '0' '0']
      ['0' '0' '0']]
    
     [['0' '0' '0']
      ['0' '0' '0']
      ['0' '0' '1']]
    
     [['0' '0' '0']
      ['0' '0' '0']
      ['0' '1' '0']]
     ...
    
    print(len(x))
    # 512