Search code examples
pythonpython-2.7combinationspython-itertools

Combination of 1 and 0 in an array in Python


I want to make a combination of 1's and 0's in a 2d array like the following:

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

That means a combination of four 1's and four 0's. I have looked at the itertools module's permutations() and combinations(), but couldn't find any suitable functions to perform this combination.


Solution

  • You can also use combinations to generate unique combinations directly:

    n = 8
    n1 = 4
    for x in itertools.combinations( xrange(n), n1 ) :
        print [ 1 if i in x else 0 for i in xrange(n) ] 
    
    [1, 1, 1, 1, 0, 0, 0, 0]
    [1, 1, 1, 0, 1, 0, 0, 0]
    [1, 1, 1, 0, 0, 1, 0, 0]
    [1, 1, 1, 0, 0, 0, 1, 0]
    ...
    [0, 0, 0, 1, 1, 1, 0, 1]
    [0, 0, 0, 1, 1, 0, 1, 1]
    [0, 0, 0, 1, 0, 1, 1, 1]
    [0, 0, 0, 0, 1, 1, 1, 1]
    

    This is more efficient than permutations because you don't iterate over unwanted solutions.

    The intuition is that you're trying to find all possible ways to fit four "1"s in a sequence of length 8; that's the exact definition of combinations. That number is C(8,4)=8! / (4! * 4!) = 70. In contrast, the solution using permutations iterates over 8! = 40,320 candidate solutions.