Search code examples
randombinarysublist

How can I generate all the possible binary lists with 4 elements? (Using Python)


I'm wondering is there a way I can generate a list whose sublists are all the possible combinations of 0 and 1 with 4 elements? To generate an individual sublist, I have

import random
binum = np.random.randint(2, size=4).tolist()

But how can I get a full list to contain all the possible sublists, each appears once? So the desired output looks like:

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

(There're 16 elements in total for this case). Thanks:)


Solution

  • Just iterate over numbers from 0 to 15 and get their binary representation:

    In [1]: N = 4    
    
    In [2]: def getbit(value, bitnum):
       ...:     mask = 1 << bitnum
       ...:     return (value & mask) >> bitnum
       ...: 
    
    In [3]: [[getbit(i, j) for j in range(N)] for i in range(2 ** N)]
    Out[3]: 
    [[0, 0, 0, 0],
     [1, 0, 0, 0],
     [0, 1, 0, 0],
     [1, 1, 0, 0],
     [0, 0, 1, 0],
     [1, 0, 1, 0],
     [0, 1, 1, 0],
     [1, 1, 1, 0],
     [0, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 1, 0, 1],
     [1, 1, 0, 1],
     [0, 0, 1, 1],
     [1, 0, 1, 1],
     [0, 1, 1, 1],
     [1, 1, 1, 1]]
    

    Same in numpy:

    np.unpackbits(np.expand_dims(np.arange(2 ** N, dtype=np.uint8), -1),
                  axis=1, bitorder='little', count=N)
    

    Also, you can generate the next element by implementing increment operation on binary array:

    def gen(l=4):
        a = [0 for _ in range(l)]
        while True:
            yield a.copy()
            i = 0
            while i < l and a[i]:
                a[i] = 0
                i += 1
            if i == l:
                break
            a[i] = 1