如何在Python中生成0-1矩阵的所有可能组合? [英] How to generate all possible combinations of 0-1 matrix in Python?

查看:435
本文介绍了如何在Python中生成0-1矩阵的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成大小为K的N的0-1矩阵的所有可能组合?



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

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


解决方案

具有 numpy 和 itertools

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

说明: 函数返回其输入的笛卡尔积。例如, product([0,1],[0,1])返回一个迭代器,该迭代器包含 [0,1]的所有可能排列 [0,1] 。换句话说,从乘积迭代器中提取:

 对于乘积中的i,j([0,1],[0, 1]):

实际上等效于运行两个嵌套的for循环:

 对于[0,1]中的i:
for j在[0,1]中:

上面的for循环已经解决了特定情况下 K的手头问题,N =(1,0) 。继续上述思路,要生成向量 i 的所有可能的零/一状态,我们需要从迭代器中提取样本,该迭代器等效于嵌套的for循环深度 l ,其中 l = len(i)。幸运的是, itertools 提供了使用 repeat 关键字参数来实现此目的的框架。对于OP的问题,此排列深度应为 K * N ,以便可以在列表理解的每个步骤中将其重新排列为适当大小的Numpy数组。 / p>

How can generate all possible combinations of a 0-1 matrix of size K by N?

For example, if I take K=2 and N=2, I get the following combinations.

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

解决方案

A one-liner solution with numpy and itertools:

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

Explanation: the product function returns a Cartesian product of its input. For instance, product([0, 1], [0, 1]) returns an iterator that comprises all possible permutations of [0, 1] and [0, 1]. In other words, drawing from a product iterator:

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

is actually equivalent to running two nested for-loops:

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

The for-loops above already solve the problem at hand for a specific case of K, N = (1, 0). Continuing the above line of thought, to generate all possible zero/one states of a vector i, we need to draw samples from an iterator that is equivalent to a nested for-loop of depth l, where l = len(i). Luckily, itertools provides the framework to do just that with its repeat keyword argument. In the case of OP's problem this permutation depth should be K*N, so that it can be reshaped into a numpy array of proper sizes during each step of the list comprehension.

这篇关于如何在Python中生成0-1矩阵的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆