There are some elegant examples of using numpy in Python to generate arrays of all combinations. For example, the answer here is: Using numpy to build an array of all combinations of two arrays .
Now suppose that there is an additional restriction, namely, the sum of all numbers cannot contain more than a given constant K Using the generator and itertools.product , for an example with K=3 , where we want a combination of three variables with ranges 0-1.0-3 and 0-2, we can do this:
from itertools import product K = 3 maxRange = np.array([1,3,2]) states = np.array([i for i in product(*(range(i+1) for i in maxRange)) if sum(i)<=K])
which returns
array([[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 3, 0], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 2, 0]])
Basically, the approach of https://stackoverflow.com/a/377832/ can be used to create all possible combinations without restriction, and then select a subset of combinations whose sum is less than K However, this approach generates many more combinations than necessary, especially if K relatively small compared to sum(maxRange) .
There must be a way to do this faster and with less memory use. How can this be achieved using a vectorized approach (e.g. using np.indices )?