繁体   English   中英

生成零和b的所有可能组合

[英]Generating all possible combinations of a zeros and b ones

有没有一种有效的方法来生成所有可能的2个1和8个零组合的列表(或数组)? 例如

[[0,0,0,0,0,0,0,0,1,1],
 [0,0,0,0,0,0,0,1,0,1,],
 ...]

这有效,但可能有更好的方法吗?

import numpy as np
result = []
for subset in itertools.combinations(range(10), 2):
    subset = list(subset)
    c = np.zeros(10)
    c[subset] = 1
    result.append(c)

希望对如何优化此代码有一些想法。

嗯,它没有太大的不同,但在Numpy数组上进行批量操作肯定会有更少的开销:

import itertools
import numpy

which = numpy.array(list(itertools.combinations(range(10), 2)))
grid = numpy.zeros((len(which), 10), dtype="int8")

# Magic
grid[numpy.arange(len(which))[None].T, which] = 1

grid
#>>> array([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 1, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
#>>> ...

大部分时间用于执行numpy.array(list(itertools.combinations(range(10), 2))) 我尝试使用numpy.fromiter但我没有得到任何速度提升。 由于一半的时间实际上是生成元组,因此进一步改进的唯一真正方法是生成C或Cython之类的组合。

替代使用numpy.bincount

>>> [np.bincount(xs, minlength=10) for xs in itertools.combinations(range(10), 2)]
[array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 1, 0, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 0, 1, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=int64),
 ...]

我们不应该为此使用排列吗? 例如,

from itertools import permutations as perm
a, b = 6, 2
print '\n'.join(sorted([''.join(s) for s in set(t for t in perm(a*'0' + b*'1'))]))

暂无
暂无

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

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