1

I am trying to produce all combination of numpy array that satisfy a condition efficiently my code now looks like this

import numpy as np
import itertools

a = np.array([1,11,12,13])
a = np.tile(a,(13,1))
a = a.flatten()

for c in itertools.combinations(a,4):
  if np.sum(c)==21:
    print(c)  
user93
  • 1,866
  • 5
  • 26
  • 45
  • a = np.tile(a,4) is sufficient for this problem. Are you looking at a general solution ? – B. M. Apr 18 '16 at 11:36

1 Answers1

0

If you only care about unique combinations (and there are only 256 of them), you can use itertools.product:

version_1 = np.vstack(list(sorted({tuple(row) for row in list(itertools.combinations(a, 4))})))  # unique combinations, your way
version_2 = np.array(list(itertools.product((1, 11, 12, 13), repeat=4)))  # same result, but faster
assert (version_1 == version_2).all()

I'm using this answer to get the unique elements of a Numpy array.

So the final answer would be:

import itertools, numpy as np
a = np.array(list(itertools.product((1, 11, 12, 13), repeat=4)))
for arr in a[a.sum(axis=1) == 21]:
    print(arr)
Community
  • 1
  • 1
1''
  • 26,823
  • 32
  • 143
  • 200