How to stop stack overflow when generating permutations in python

I am trying to create permutations in python without using itertools. This is my code:

def generatePermutations(minVal, maxVal, arrayLength, depth = -1, array = []):
    if(depth == -1): # set all values to minVal initially
        for i in range(arrayLength):
            array.append(minVal)
        depth += 1
        generatePermutations(minVal, maxVal, arrayLength, depth, array) # recurse

    elif depth < arrayLength:
        a.append(array[:]) # a is a list declared above the function

        current = 0
        while current <= depth:
            if array[current] < maxVal:
                array[current] += 1
                break
            else:
                if current < depth:
                    array[current] = minVal
                else:
                    depth += 1
                    array[current] = minVal
                    if depth < arrayLength:
                        array[depth] += 1
                    break
            current += 1

        generatePermutations(minVal, maxVal, arrayLength, depth, array)

The function works for a fairly small set of numbers. For example, generatePermutations(1,2,2)populates the list aas follows:

[1, 1]
[2, 1]
[1, 2]
[2, 2]

But, when I try to create an array permutation of length 9 ( generatePermutations(1,9,9)), I run the error long before the function completes. Is there any way to prevent this?

+4
source share
1 answer

, , , . , , . generatePermutations(1,9,9), Python 9!=362880, ( 1000).

, a, . , 9 .

+3

Source: https://habr.com/ru/post/1617183/


All Articles