问题
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.
回答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 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
回答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:
def get_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]]
来源:https://stackoverflow.com/questions/54923928/python-generate-all-possible-combinations-of-matrix