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 possibl
Solution 1:
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 inrange(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
Solution 2:
If you want all matrices at once, just produce flat lists using itertools.product
and numpy.reshape
them:
from itertools import product
import numpy as np
n, m = 2, 2
x = product([1, 0], repeat=n*m)
x = np.reshape(list(x), (-1, n, m))
print(x)
With the output for 2x2:
array([[[1, 1],
[1, 1]],
[[1, 1],
[1, 0]],
[[1, 1],
[0, 1]],
[[1, 1],
[0, 0]],
[[1, 0],
[1, 1]],
[[1, 0],
[1, 0]],
[[1, 0],
[0, 1]],
[[1, 0],
[0, 0]],
[[0, 1],
[1, 1]],
[[0, 1],
[1, 0]],
[[0, 1],
[0, 1]],
[[0, 1],
[0, 0]],
[[0, 0],
[1, 1]],
[[0, 0],
[1, 0]],
[[0, 0],
[0, 1]],
[[0, 0],
[0, 0]]])
Note that for n, m = 16, 16
there are 2**(16*16)
combinations, which is about 10**77
, so much too large to fit into memory. In that case you probably have to process each matrix on its own:
defget_combinations(n, m):
for flat in product([1, 0], repeat=n*m):
yield np.reshape(flat, (n, m))
Which you can use like this:
from itertools import islice
for m in islice(get_combinations(3, 3), 3): # only get the first three
print(m)
[[1 1 1]
[1 1 1]
[1 1 1]][[1 1 1]
[1 1 1]
[1 1 0]][[1 1 1]
[1 1 1]
[1 0 1]]
Post a Comment for "Python Generate All Possible Combinations Of Matrix"