简体   繁体   English

使用python遍历所有可能的numpy二进制数组

[英]Iterate over all possible numpy binary arrays with restrictions using python

I'm trying to iterate over all possible binary arrays of size mxn but with some restrictions. 我试图遍历所有可能的大小为mxn的二进制数组,但有一些限制。 As you know the set of arrays becomes extreme as m and n increase (2^(m*n) arrays). 如您所知,随着m和n的增加,数组的集合变得极端(2 ^(m * n)个数组)。 I have written some code that will iterate over all of these possibilities. 我写了一些代码,将迭代所有这些可能性。

mxn = np.arange(m*n).reshape(m,n)
for i in xrange(0, 2**(m*n)):
    arr = (i >> mxn) % 2
    print arr

I can add some additional restrictions that reduce the arrays I need to iterate over. 我可以添加一些其他限制来减少需要迭代的数组。 The restrictions are that each row in the matrix can sum to no more than 1. The second restriction is that the sum of all of the elements in the matrix cannot be greater than m. 限制条件是矩阵中的每一行的总和不能超过1。第二个限制条件是矩阵中所有元素的总和不能大于m。 Can I modify what I already have to accomplish this, or is there an altogether different path that I should be going down? 我可以修改已经完成此操作的内容,还是应该走一条完全不同的路径?

Since the matrix is of size m*n , the second restriction will be automatically met if the first one is satisfied. 由于矩阵的大小为m*n ,如果满足第一个条件,则第二个条件将自动得到满足。

Since each row has at most 1 element to be none zero, there are only n+1 choices for a row. 由于每一行最多有1个元素都不为零,因此一行只有n+1选择。 Given there is m rows, the possible number of combinations for such a matrix is thus (n+1)**m . 给定有m行,因此此矩阵的组合数量可能为(n+1)**m The following code then reduces the complexity from 2**(m*n) to (n+1)**m . 然后,以下代码将复杂度从2**(m*n)(n+1)**m

rows = []
r = np.zeros((n,), dtype=np.int)
rows.append(r)
for i in range(n):
    r = np.zeros((n,), dtype=np.int)
    r[i] = 1
    rows.append(r)

rows = np.array(rows)

arr = np.zeros((m,n), dtype=np.int)
idx = [0]*m
base = np.array([(n+1)**j for j in range(m)])
for i in xrange(0, (n+1)**m):
    idx = (i / base) % (n+1)
    print rows[idx]

The same algorithm as @pyan, but use numpy functions: 与@pyan相同的算法,但使用numpy函数:

import numpy as np

m, n = 2, 3
rows = np.vstack([np.zeros(n, dtype=np.int), np.identity(n, dtype=np.int)])
index = np.indices([len(rows)] * m).reshape(m, -1).T
rows[index]

output is a 3d array: 输出是一个3D数组:

[[[0 0 0]
  [0 0 0]]

 [[0 0 0]
  [1 0 0]]

 [[0 0 0]
  [0 1 0]]

 [[0 0 0]
  [0 0 1]]

 [[1 0 0]
  [0 0 0]]

 [[1 0 0]
  [1 0 0]]

 [[1 0 0]
  [0 1 0]]

 [[1 0 0]
  [0 0 1]]

 [[0 1 0]
  [0 0 0]]

 [[0 1 0]
  [1 0 0]]

 [[0 1 0]
  [0 1 0]]

 [[0 1 0]
  [0 0 1]]

 [[0 0 1]
  [0 0 0]]

 [[0 0 1]
  [1 0 0]]

 [[0 0 1]
  [0 1 0]]

 [[0 0 1]
  [0 0 1]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM