2016-10-09 84 views
3

怎样才能生成大小为K的0-1矩阵的所有可能的组合?如何在Python中生成0-1矩阵的所有可能组合?

例如,如果我采取K = 2和N = 2,我得到以下组合。

combination 1 
[0, 0; 
0, 0]; 
combination 2 
[1, 0; 
0, 0]; 
combination 3 
[0, 1; 
0, 0]; 
combination 4 
[0, 0; 
1, 0]; 
combination 5 
[0, 0; 
0, 1]; 
combination 6 
[1, 1; 
0, 0]; 
combination 7 
[1, 0; 
1, 0]; 
combination 8 
[1, 0; 
0, 1]; 
combination 9 
[0, 1; 
1, 0]; 
combination 10 
[0, 1; 
0, 1]; 
combination 11 
[0, 0; 
1, 1]; 
combination 12 
[1, 1; 
1, 0]; 
combination 13 
[0, 1; 
1, 1]; 
combination 14 
[1, 0; 
1, 1]; 
combination 15 
[1, 1; 
0, 1]; 
combination 16 
[1, 1; 
1, 1]; 
+0

更像是一个算法问题 - > http://programmers.stackexchange.com/ – tomasyany

回答

5

numpyitertools和一个一衬垫溶液:

[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)] 

说明:product函数返回其输入的笛卡儿积。例如,product([0, 1], [0, 1])返回包含所有可能的排列[0, 1][0, 1]的迭代器。上述手头已经解决的问题的特定情况下

for i in [0, 1]: 
    for j in [0, 1]: 

的for循环:换句话说,从产品迭代绘制:

for i, j in product([0, 1], [0, 1]): 

实际上相当于运行两个嵌套的for循环K, N = (1, 0)。继续上述思路,为了生成矢量的所有可能的零/一个状态,我们需要从迭代器中抽取样本,该迭代器相当于嵌套的深度为l的循环,其中l = len(i)。幸运的是,itertools提供了一个框架,可以用它的repeat关键字参数来做到这一点。在OP问题的情况下,这个置换深度应该是K*N,以便在列表理解的每个步骤期间它可以被重新塑造成适当大小的数组。

相关问题