Python生成所有可能的矩阵组合

Con*_*uto 4 python math combinations list

我需要在Python中生成矩阵的所有组合.输入将是两个整数n和m,我需要生成该矩阵的所有可能状态,其中1和0为可能的值.

例如:

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] . . . . .
]
Run Code Online (Sandbox Code Playgroud)

有没有一种干净有效的方法可以做到这一点,因为我不知道运行时n和m的值?使用的最高值是n = 16 m = 16.

Gra*_*her 5

如果您想要一次使用所有矩阵,只需使用它们生成平面itertools.product列表numpy.reshape

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)
Run Code Online (Sandbox Code Playgroud)

输出为 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]]])
Run Code Online (Sandbox Code Playgroud)

请注意,因为n, m = 16, 16有一些2**(16*16)组合,大约是10**77,太大而无法装入内存。在这种情况下,您可能必须单独处理每个矩阵:

def get_combinations(n, m):
    for flat in product([1, 0], repeat=n*m):
        yield np.reshape(flat, (n, m))
Run Code Online (Sandbox Code Playgroud)

你可以这样使用:

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]]
Run Code Online (Sandbox Code Playgroud)


yat*_*atu 5

一种方法是通过m*n在列表推导中生成所有长度的二进制序列,并(m,n)在每次迭代时将它们重新整形为形状嵌套列表.

生成所有序列的一种简单方法是01使用n*m重复的笛卡尔积,这将产生2^(m*n)组合:

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)]
Run Code Online (Sandbox Code Playgroud)

产量

[[['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
Run Code Online (Sandbox Code Playgroud)