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)
[[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
CodePudding user response:
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.
CodePudding user response:
with just numpy,we can use np.unpackbits
bits = 4
np.unpackbits(np.arange(bits**2, dtype=np.uint8)[...,None], count=bits, axis=1, bitorder='little')
CodePudding user response:
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.
