gpt4 book ai didi

python - 这个函数即使不调用自身也是递归的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:52 24 4
gpt4 key购买 nike

from pythonds.basic.stack import Stack

rStack = Stack()

def toStr(n,base):
convertString = "0123456789ABCDEF"
while n > 0:
if n < base:
rStack.push(convertString[n])
else:
rStack.push(convertString[n % base])
n = n // base
res = ""
while not rStack.isEmpty():
res = res + str(rStack.pop())
return res

print(toStr(1345,2))

我指的是 this tutorial 并且还粘贴了上面的代码。该教程说该函数是递归的,但我在任何地方都看不到递归调用,只是一个 while 循环。我错过了什么?

最佳答案

你是对的,这个特定的函数不是递归的。然而,上下文是,在上一张幻灯片中有一个递归函数,而在这张幻灯片中,他们想展示一下它的内部行为。他们后来说:

The previous example [i.e. the one in question - B.] gives us some insight into how Python implements a recursive function call.

所以,是的,标题具有误导性,它应该是扩展递归函数用堆栈模拟递归函数行为或类似的东西。

有人可能会说这个函数在某种意义上采用了递归的方法/策略来解决要解决的问题,但它本身并不是递归的。

关于python - 这个函数即使不调用自身也是递归的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com