user2696794
user2696794

Reputation: 111

How can I enumerate all the possible N-long combinations of zeros and ones in Python?

I'd like to enumerate all the possible N-long lists of zeros and ones : [0,1,0,0,0,1,0,...]. So, basically an 2^N-long matrix of N-long elements. If N=3, I would do the following:

M = []
for i in range(2):
    for j in range(2):
        for k in range(2):
            M.append([i,j,k])

I need a simpler way to do that for an arbitrary N (N<20). Thanks.

Upvotes: 3

Views: 137

Answers (3)

senshin
senshin

Reputation: 10360

If you're a fan of itertools (and really, who isn't?), you can use itertools.product to take a repeated Cartesian product of the binary digits [0, 1]. Set the repeat argument set to whatever length you want.

>>> import itertools
>>> length = 3
>>> for thing in itertools.product([0, 1], repeat=length): print(thing)

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

As a general rule of thumb, if you find yourself nesting a lot of similar-looking loops, there's probably a better way of solving your problem that involves using itertools.

Upvotes: 4

dfb
dfb

Reputation: 13289

def binstr(n):
    if n == 0:
        return [""]
    else:
        rec = binstr(n-1)
        return ["0"+x for x in rec] + ["1"+x for x in rec]

Upvotes: 3

advocateofnone
advocateofnone

Reputation: 2541

You can do that as follows

         M = []
         for i in range ( 1<< N ):
             tmp = i
             bit_string=[]
             for j in range(N):
                 bit_string.append(tmp%2)
                 tmp = tmp/2
             M.append(bit_string)

Upvotes: 2

Related Questions