Python 3.x 将迭代代码转换为递归代码Python3
我是一名编程初学者,最近一直在学习Python3中的递归函数。我正在编写一个代码,该代码基本上提供了一个数字N为m所需的最少步骤,这个过程包括加1、除2或多个10。我做了一个很好的迭代函数,但作为递归函数的初学者,我希望能够将代码转换为递归代码,但在这段代码中我没有成功。Python 3.x 将迭代代码转换为递归代码Python3,python-3.x,recursion,iteration,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))
示例
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
非常感谢。我改变了一些结构以适应我的目标,我能够实现它。