我有未知数量的整数变量,其范围为 [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/