Python 将递归排列函数转换为迭代



我有一个未知数量的整数变量,说范围可以从 [0,9]我想遍历这些值的所有排列。

如果变量的数量是恒定的,则很容易编写嵌套的循环。 我想出了一个递归函数,可以做我想做的事,但很好奇是否有办法迭代地做到这一点。

def nested(array,index):
    n = len(array)
    for i in range(10):
        array[n-index]=i
        #len(array-1) end of array
        if(index == 1):
            print(array)
            #do something later
        else:
            nested(array,index-1)
#generate all permutations, change n to change size of list.            
n = 4
array = [0]*n
nested(array,len(array))

我尝试使用此处找到的所谓"简单方法"-> http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html但我无法让它工作。

正如另一位评论者所提到的,关键是使用堆栈模拟尾部递归。

请注意,我在stackappend()了一个(array, index)元组,它反映了原始递归解决方案中对递归函数的调用。在迭代开始时,它确实stack.pop(),这模仿了递归函数的主体。递归调用变为stack.append()

def nested(array):
    stack = []
    n = len(array)
    stack.append((array.copy(), n))
    while(stack):
        array, index = stack.pop()        
        for i in range(10):
            array[n-index]=i
            #len(array-1) end of array
            if(index == 1):
                print(array)
                #do something later
            else:
                stack.append((array.copy(), index-1)) 
#generate all permutations, change n to change size of list.            
n = 4
array = [0]*n
nested(array)

请参考迭代工具。有一个类"排列"可以完美地解决你的问题。

最新更新