簡體   English   中英

Python生成所有可能的矩陣組合

[英]Python generate all possible combinations of matrix

我需要在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] . . . . .
]

有沒有一種干凈有效的方法來實現這一點,因為我不知道運行時n和m的值? 使用的最高值是n = 16 m = 16。

一種方法是通過在列表推導中生成長度為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)]

產量

[[['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

如果您想同時使用所有矩陣,只需使用itertools.productnumpy.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)

輸出為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]]])

注意,對於n, m = 16, 162**(16*16)組合,大約10**77 ,太大而不適合存儲器。 在這種情況下,您可能必須自己處理每個矩陣:

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

您可以這樣使用:

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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM