简体   繁体   中英

How to Use Recursion to Generate Arrays in Python

I am trying to generate all possible arrays with values from 1 - 9 using recursion in python. My code is below:

totalArr = []

def recursion(arr, n):
    for i in range(9):
        if (arr[i] == 0):
            arr[i] = n
            if (n < 8):
                recursion(arr, n + 1)
            else:
                print(arr)
                totalArr.append(arr)

recursion([0, 0, 0, 0, 0, 0, 0, 0, 0], 0)

print(len(totalArr))

When I run this code, all I get is the single array below:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

I am aware that I can use permutations to the arrays, however for my use case of these arrays, I believe that recursion is better in the long run.

totalArr=[]
def permute(lst,n):
    ''' O(n!), optimal'''
    if n==1:totalArr.append(lst.copy())
    else:
        for i in range(n):
            lst[i],lst[n-1] = lst[n-1],lst[i]
            permute(lst,n-1)
            lst[i],lst[n-1] = lst[n-1],lst[i]
lst = [i for i in range(1,9)] # any other lst with unique elements is ok
permute(lst,len(lst))
print(totalArr)

This method can generate all permutations using divide-and-conquer algorithm

# Python program to print all permutations with
# duplicates allowed

# Function to print permutations of my_array
# This function takes three parameters:
# 1. my_array
# 2. Starting index of the my_array
# 3. Ending index of the my_array.
def permute(a, l, r):
    if l==r:
        print a
    else:
        for i in xrange(l,r+1):
            a[l], a[i] = a[i], a[l]
            permute(a, l+1, r)
            a[l], a[i] = a[i], a[l] # backtrack

# Driver program to test the above function
my_array = [0,1,2,3,4,5,6,7,8,9]
n = len(my_array)
a = list(my_array)
permute(a, 0, n-1)

We are doing permutation by using recursion with backtracking : More info on https://www.geeksforgeeks.org/write-ac-program-to-print-all-permutations-of-a-given-string/

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