簡體   English   中英

如何在python中生成排列時阻止堆棧溢出

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

我試圖在不使用itertools情況下在python中生成排列。 到目前為止,這是我的代碼:

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)

該功能適用​​於足夠小的數字。 例如, generatePermutations(1,2,2)使用以下內容填充列表a

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

但是,當我嘗試創建長度為9的數組( generatePermutations(1,9,9) )的排列時,我會在函數完成之前很久就遇到堆棧溢出錯誤。 有沒有辦法阻止這種情況?

我做了一些測試,我發現你的功能設置方式,它自稱為每一個排列 同樣,遞歸深度與到目前為止生成的排列數相同。 當你嘗試執行generatePermutations(1,9,9) ,Python會嘗試遞歸到9!=362880深度,這太深了(它被限制為1000 )。

相反,重構您的代碼,以便迭代a每個元素,附加當前數字,並在每個數字的循環中執行此操作。 這樣,遞歸只需要達到9級深度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM