当函数中存在循环时,将递归转换为迭代

2024-05-29 03:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将代码库中的一些递归调用转换为迭代。多亏了this blogthis question,这一点非常简单。然而,下面的模式(作为一个最小的例子)让我很难接受。它基本上给出了n^m位置上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,这应该是可能的。如果有人能分享一些关于如何进行这一转换的指导,那将是非常好的


Tags: 代码inforlenifdef模式blog
1条回答
网友
1楼 · 发布于 2024-05-29 03:30:40

从代码中退一步,考虑一下您试图在这里生成的模式可能会有所帮助。例如,假设每个插槽有十个数字选项可供选择,它们是0、1、2、…、9。在这种情况下,您所做的基本上是从000开始向上计数,直到最终达到999。你是怎么做到的?嗯:

  • 如果最后一位数字不是9,则添加一位。你完了
  • 否则,数字为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

相关问题 更多 >

    热门问题