将迭代代码转换为递归代码Python3

时间:2020-10-28 15:35:16

标签: python-3.x recursion iteration

我是一名编程初学者,最近我一直在研究Python3中的递归函数。我正在编写的代码基本上提供了最少的步骤,要求数N等于M经历加1,除2或乘以10的过程。我做了一个迭代函数,效果很好,但是作为递归函数的初学者我希望能够将代码转换为递归代码,但在此代码中我没有成功。

我最近一直在阅读有关此过程的信息,但是正如我所说的那样,这对我的技能而言是非常困难的实现。我知道是否要转换迭代代码,我需要使用主循环条件作为我的基本情况,并使用循环主体作为递归步骤,这就是我所知道的。
如果您能帮助我找到此代码的基本情况和递归步骤,我将非常感激。 我不想你写我的代码,我希望你能帮助我实现我的目标。

迭代代码

def scape(N, M, steps=0):
    if N == M:
        return 0

    currentoptions = [N]

    while True:
        if M in currentoptions:
            break

        thisround = currentoptions[:]
        currentoptions = []

        for i in thisround:
            if (i%2) == 0:
                currentoptions.append(i // 2)
            currentoptions.append(i + 1)
            currentoptions.append(i * 10)

        steps += 1

    return steps

示例

print(scape(8,1))

输出-> 3 因为8/2-> 4/2-> 2/2 = 1

1 个答案:

答案 0 :(得分:1)

这里很难使用纯递归(不传递辅助数据结构)。您可以按照以下方式做某事:

def scape(opts, M, steps=0):
    if M in opts:
        return steps
    opts_ = []
    for N in opts:
        if not N%2:
            opts_.append(N // 2)
        opts_.extend((N + 1, N * 10))
    return scape(opts_, M, steps+1)

>>> scape([8], 1)
3

或者为了保留签名(而不传递多余的参数),可以使用递归帮助器函数:

def scape(N, M):
    steps = 0
    def helper(opts):
        nonlocal steps
        if M in opts:
            return steps
        opts_ = []
        for N in opts:
            if not N%2:
                opts_.append(N // 2)
            opts_.extend((N + 1, N * 10))
        steps += 1
        return helper(opts_)
    return helper([N])

>>> scape(8, 1)
3
相关问题