【问题标题】:Generate all possible binary matrices of size N x M (Python)生成所有可能的大小为 N x M (Python) 的二进制矩阵
【发布时间】:2019-01-27 21:20:50
【问题描述】:
我知道还有其他与此类似的问题会生成具有某些属性的矩阵,但我希望生成给定大小的所有可能矩阵,除了 Python 中的条目是 1 或 0 之外没有任何限制.我该怎么做?
【问题讨论】:
标签:
python
matrix
combinations
【解决方案1】:
我在一行中做到了(开玩笑的)
def gen(n, m):
for i in range(2**(n*m)):
yield np.array([int(k) for k in "{0:b}".format(i).zfill(n*m)]).reshape(n,m)
这种工作方式有点像 hack,我用二进制数计数并用这些位填充数组。
如果您不熟悉生成器/迭代器,只需看看如何使用它:
for mat in gen(3, 5): pass # mat goes threw every possible array (uses virtually no memory)
l = list(gen(3, 5)) # array of all possible arrays (uses a lot of memory)