简体   繁体   中英

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

Wrote this script to create a 4x16 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.. just started learning python, and the only other language I know is MATLAB

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.

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')

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)]

PS It is good to learn about Recursion .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM