python - 当函数中有循环时将递归转换为迭代

标签 python algorithm recursion iteration enumeration

我正在将代码库中的一些递归调用转换为迭代。这非常简单,感谢 this blog ,和this question 。然而,有以下模式(作为一个最小的例子),这让我很难过。它基本上给出了 m 个位置上的 n 个数字的 n^m 排列(有重复)(这里 n=4m=3):

def f (i, arr):
    if i < len(arr):
        for j in [2,3,5,8]:
            arr[i] = j
            f(i+1, arr)
    else:
        print(arr)

f(0, [0,0,0])

输出:

[2, 2, 2]
[2, 2, 3]
[2, 2, 5]
...
[8, 8, 3]
[8, 8, 5]
[8, 8, 8]

根据this discussion ,这应该是可能的。如果有人可以分享一些有关如何进行此转换的指导,那就太好了?

最佳答案

从代码中退后一步并思考您要在此处生成的模式可能会有所帮助。例如,想象一下,每个槽有 10 个数字可供选择,它们是 0、1、2、...、9。在这种情况下,您所做的实际上是从 000 开始向上计数,直到你最终达到了 999。你是如何做到的呢?嗯:

  • 如果最后一位数字不是 9,则加 1。你已经完成了。
  • 否则,该数字是 9。将其回滚到 0,然后移至前面的数字。

在你的例子中,它是数字 2、3、5 和 8,但这并不重要。

您可以将其转换为一个很好的过程,用于解决更普遍的问题,即列出从 k 个选项列表中取出的 n 个符号的所有写法:

def list_all_options(length, options):
    # Initially, pick the first option in each slot. This array stores
    # indices rather than values.
    curr = [0] * length
    
    while True:
        # Print what we have, mapping from indices to values.
        print([options[index] for index in curr])
        
        # Roll over all copies of the last digit from the end, backing
        # up as we go.
        pos = len(curr) - 1
        while pos >= 0 and curr[pos] == len(options) - 1:
            curr[pos] = 0
            pos -= 1
        
        # If we rolled all digits, we're done!
        if pos == -1: break
        
        # Otherwise, increment this digit.
        curr[pos] += 1

关于python - 当函数中有循环时将递归转换为迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63925105/

相关文章:

c++ - C++中的尾递归

python - 在较长列表的每个第 n 个元素处将两个不同长度的列表组合成元组

python - 如何用 None 替换字符串值 - python,pandas dataframe

algorithm - 寻求保留重复项的合并算法

algorithm - 如何从包含给定点的一组点中找到最小的 N 维单纯形?

algorithm - 找到在每一行和每一列中只选择一个的矩阵 (n x n) 的最小总和

java - 按升序打印二进制数

python - python oop 中的委托(delegate)

python - 按模式查找 boolean 掩码

c++ - 如何创建返回与函数具有相同签名的仿函数的函数?