简体   繁体   English

如何在python中生成排列时阻止堆栈溢出

[英]How to stop the stack from overflowing when generating permutations in python

I'm trying to generate permutations in python without using itertools . 我试图在不使用itertools情况下在python中生成排列。 This is my code thus far: 到目前为止,这是我的代码:

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 small enough set of numbers. 该功能适用​​于足够小的数字。 For example, generatePermutations(1,2,2) populates list a with the following: 例如, generatePermutations(1,2,2)使用以下内容填充列表a

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

But, when I try to create permutations of an array of length 9 ( generatePermutations(1,9,9) ), then I run into a stack overflow error long before the function is finished. 但是,当我尝试创建长度为9的数组( generatePermutations(1,9,9) )的排列时,我会在函数完成之前很久就遇到堆栈溢出错误。 Is there any way of preventing this? 有没有办法阻止这种情况?

I did a little testing, and I found that the way your function is set up, it calls itself for every single permutation . 我做了一些测试,我发现你的功能设置方式,它自称为每一个排列 As in, the recursion depth is the same as the number of permutations generated so far. 同样,递归深度与到目前为止生成的排列数相同。 When you try to do generatePermutations(1,9,9) , Python tries to recurse to 9!=362880 levels deep, which is far too deep (it's limited to 1000 ). 当你尝试执行generatePermutations(1,9,9) ,Python会尝试递归到9!=362880深度,这太深了(它被限制为1000 )。

Instead, refactor your code so that you iterate over each element in a , appending the current digit, and do this in a loop for each digit. 相反,重构您的代码,以便迭代a每个元素,附加当前数字,并在每个数字的循环中执行此操作。 This way, the recursion will only have to go 9 levels deep. 这样,递归只需要达到9级深度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM