This is a bad example for list comprehensions when N
is really large, as you'll need N
variables with for i in xrange(2)
when each is either on or off, but its rather straightforward to do with itertools.combination
For example to clone your N=3
example:
results = []
for w in range(1,4):
results += [[i,j,k] for i in xrange(2) for j in xrange(2) for k in xrange(2) if i+j+k ==w]
where you get results as: [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Now the following using itertools.combination is trivial to scalably extend to larger N.
import itertools
results = []
N=3
for w in range(1,N+1):
results += list(itertools.combinations(range(N),w))
where you get results as [(0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]
, that is return the indices of the variables that are non-zero.
This can be trivially turned into the other form, e.g.:
for index_tuple in results:
new = [0]*N
for i in index_tuple:
new[i] = 1
new_results.append(new)
where new_results
has the same form [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
and can be trivially extended to larger N. (Granted it's probably better to keep it in the first form, or use something like numpy for efficient use of masking arrays).