python生成一列有0有1的矩阵_如何在Python中生成0-1矩阵的所有可能组合?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值