简体   繁体   中英

How to generate all configurations of a given length in Python

I am trying to generate a list of all configurations where in each configuration is as follows. Each configuration is a list of length n whose entry can take on values 0-q where q is a positive integer. For example if q=1 then I am trying to generate a list of all possible binary lists of length n . So if n=2,q=1 then the desired output is [[0,0],[0,1],[1,0],[1,1]] . For an arbitrary q , the desired output list is of size (q+1)^n because there q+1 choices for each element of the list of length n . For example, for n=3,q=2 , the desired output is [[0,0,0],[0,0,1],[0,0,2],[0,1,0],..] and the output list is of size 3^3=27 .

I have tried to do this using recursion for q=1 but am not sure how to write efficient code for arbitrary q ? Here is the code and output for q=1 .

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

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

>>[[0,0],[0,1],[1,0],[1,1]]

itertools.product does what you want:

def generate_configurations(n,q):
    return [list(p) for p in itertools.product(range(q+1),repeat = n)]

print(generate_configurations(2,1))

#[[0, 0], [0, 1], [1, 0], [1, 1]]

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