【问题标题】:Converting Iterative Code to Recursive Code Python3将迭代代码转换为递归代码 Python3
【发布时间】:2021-02-11 00:23:12
【问题描述】:

我是一名编程初学者,最近一直在研究 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

【问题讨论】:

    标签: python-3.x recursion iteration


    【解决方案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
    

    【讨论】:

    • 谢谢!我改变了一些结构以适应我的目标,我可以实现它。
    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2019-05-18
    • 2016-01-26
    • 2017-03-05
    相关资源
    最近更新 更多