【发布时间】: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