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

标签 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 但我无法让它发挥作用。

最佳答案

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

请注意,我append()(array, index)元组添加到stack中,这反射(reflect)了对递归函数的调用你原来的递归解决方案。在迭代开始时,它会执行 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)

关于Python将递归排列函数转换为迭代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507058/

相关文章:

javascript - 遍历json树结构并将所有节点添加到列表中

python - 在 Python 的每次迭代中更改名称以保存

python - 如何使用 Flask 填充选择标签?

kotlin - 如何递归地实现对 Iterable 的深度扁平化?

python - python 中 testdome 的训练组合

arrays - 数组中的反转,我错了什么。请查看下面的数学/伪代码

c++ - 努力将在一个函数中创建的数组传递给排序函数

python - 如果其他列中的字符串包含列表中的内容,则更新一列中的值

python默认配置变量重用

python - 如何获取 Pandas 系列中某个值出现的比例?