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

问题描述

我正在将代码库中的一些递归调用转换为迭代。多亏了this blogthis question,这非常简单。但是,有以下模式(作为最小示例),这给我带来了困难。它基本上在let object = JSON.parse(localStorage.getItem("image")) var imageB64 = object.image 个位置(此处为let imageB64 = JSON.parse(localStorage.getItem("image")).image n^m)中为n个数字m个排列(重复):

n=4

输出

m=3

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

解决方法

从代码中退后一步,然后考虑您要在此处生成的模式可能会有所帮助。例如,想象一下,每个插槽有十个数字可供选择,它们分别是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