Python将递归置换函数转换为迭代

时间:2019-04-04 02:37:58

标签: python recursion iteration

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

如果变量的数量是恒定的,则很容易编写嵌套的for循环。我想出了一个可以执行我想要的功能的递归函数,但对是否有一种迭代的方法感到好奇。

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 但是我无法使其正常工作。

2 个答案:

答案 0 :(得分:1)

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

请注意,我将public abstract class Employee { public int Id { get; set; } public string Name { get; set; } } public class Programmer : Employee { double HRate { get; set; } } public class Engineer: Employee { double MRate { get; set; } } 的元组append()放入了(array, index)中,这反映了原始递归解决方案中对递归函数的调用。在迭代开始时,它执行stack,它模仿了递归函数的主体。递归调用变为stack.pop()

stack.append()

答案 1 :(得分:0)

请参阅itertools。有一个“排列”类可以完美解决您的问题。