Creating all possible combinations of zeros and b units

Is there an efficient way to create a list (or array) of all possible combinations of 2 and 8 zeros? For instance.

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

It works, but maybe the best way?

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)

I would like to have some ideas on how to optimize this code.

+4
source share
3 answers

Well, this is not much different, but doing bulk operations with Numpy arrays involves much less overhead:

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.

+4

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),
 ...]
+1

Shouldn't we use permutations for this? For instance,

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'))]))
0
source

All Articles