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



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

这里很难使用纯递归(不传递辅助数据结构(。你可以做以下事情:

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

最新更新