Search code examples
pythonnumpypython-itertools

Get all permutations of bool array


I need all permutations of a bool array, the following code is inefficient, but does what I want:

from itertools import permutations
import numpy as np
n1=2
n2=3

a = np.array([True]*n1+[False]*n2)

perms = set(permutations(a))

However it is inefficient and fails for long arrays. Is there a more efficent implementation?


Solution

  • What about sampling the combinations of indices of the True values:

    from itertools import combinations
    import numpy as np
    
    a = np.arange(n1+n2)
    
    out = [np.isin(a, x).tolist() for x in combinations(range(n1+n2), r=n1)]
    

    Output:

    [[True, True, False, False, False],
     [True, False, True, False, False],
     [True, False, False, True, False],
     [True, False, False, False, True],
     [False, True, True, False, False],
     [False, True, False, True, False],
     [False, True, False, False, True],
     [False, False, True, True, False],
     [False, False, True, False, True],
     [False, False, False, True, True]]