How do you define an array in python whose input is a binary counter?

Question:

Wrote this script to create a 4×16 matrix for all possible combinations of 4 bits:

import numpy as np
    a = []
    for x in range(2):
        for y in range(2):
            for z in range(2):
                for w in range(2):
                 a.append([x,y,z,w])
    a = np.array(a)
    print(a)

Output

[[0 0 0 0]
 [0 0 0 1]
 [0 0 1 0]
 [0 0 1 1]
 [0 1 0 0]
 [0 1 0 1]
 [0 1 1 0]
 [0 1 1 1]
 [1 0 0 0]
 [1 0 0 1]
 [1 0 1 0]
 [1 0 1 1]
 [1 1 0 0]
 [1 1 0 1]
 [1 1 1 0]
 [1 1 1 1]]

It works.. however it’s 4 loops for 4 bits. Raising the number of bits means more loops, does anyone have another way of doing this?

Haven’t tried much.. new to programming

Asked By: Dordini Balbozhia

||

Answers:

You can just use itertools.product:

list(itertools.product(range(2), repeat=4))

Here range(2) provides the 0 and 1, and then repeat=4 says 4 bits. If you want 20 bits, use repeat=20.

This result actually gives you a list, but if you want to iterate through each option one at a time, just use itertools.product(range(2), repeat=4) on its own, as this gives you a generator. For larger numbers of bits, the number of combinations might not fit in memory. Using the generator version means you only ever have one combination in memory at a time.

Answered By: Kraigolas

You can use recursion:

def create_matrix(n, arr=[]):
    if n == 0:
        print(arr)
    else:
        for i in range(2):
            create_matrix(n-1, arr + [I])

output:

> create_matrix(4)
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[0, 1, 1, 1]
[1, 0, 0, 0]
[1, 0, 0, 1]
[1, 0, 1, 0]
[1, 0, 1, 1]
[1, 1, 0, 0]
[1, 1, 0, 1]
[1, 1, 1, 0]
[1, 1, 1, 1]

This can be used to generate a matrix for all possible combinations of any bits.

It appends a 0 or 1 to arr and passes it on to the next recursive call until n leads to 0. When n becomes 0, it prints out arr.


UPDATE

As @Pranav Hosangadi suggestions, I’ve modified the code to get rid of mutable default argument and to has the return statement.

def create_matrix(n):
    if n == 0:
        return [[]]
    else:
        return [[i] + item for i in range(2) for item in create_matrix(n-1)]

P.S. It is good to learn about Recursion.

Answered By: JayPeerachai

with just numpy,we can use np.unpackbits

bits = 4
np.unpackbits(np.arange(2**bits, dtype=np.uint8)[...,None], count=bits, axis=1, bitorder='little')
Answered By: V.M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.