Generating all binary combinations of 2d array in Python

Question:

I am trying to generate all possible 2D arrays (of size n*n) of 0 and 1. Since there are two choices for each entry of the 2D array, there are 2^{n^2} such arrays that need to be generated.

I have a code that generates all possible 1D arrays (of size n) of 0 and 1. It is:

def generateAllSpinConfigs(n,arr,l,i):
    if i == n: 
        l.append(arr[:]) 
        return

    arr[i] = 0
    generateAllSpinConfigs(n,arr,l,i+1)  
    arr[i] = 1
    generateAllSpinConfigs(n,arr,l,i+1)  

    return l

arr=[None]*n 
l=[]
answer=generateAllSpinConfigs(n,arr,l,0)

I understand how that works. In this recursive code, the lowest function call returns an array of all 0 first, then an array with all 0 with a 1 in the last location and so on.
Can we extend this logic to generate all 2D arrays or is there a Python function that does the job that I’m not aware of?

Asked By: q2w3e4

||

Answers:

You can use itertools.product. First to generate 1-dimensional lists, and then again to use that as a basis to increase the dimension:

from itertools import product

def get_bin_rows(size):
    return product(range(2), repeat=size)

def get_bin_matrices(size):
    return product(get_bin_rows(size), repeat=size)

Example use for n=2:

for matrix in get_bin_matrices(2):
    # print matrix row by row
    for row in matrix:
        print(*row)
    print()  # separate matrix outputs
Answered By: trincot
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.