我试图理解双重递归,但我什么也没得到。
def f(s):
if len(s) <= 1:
return s
return f(s[1:]) + s[0]
print f('world')
借用
如果正确,上述代码将执行以下操作:
然后:
因此将如上所述打印dlrow。
当您将其设为双递归时,我无法理解代码:
def f(s):
if len(s) <= 1:
return s
else:
return f(f(s[1:])) + s[0] #Note double recursion
print f('world')
有人可以向我解释这种双重递归如何工作吗?
在2019年,使用在线编译器(例如www.onlinegdb.com/online_python_compiler),上述打印行不起作用。这是工作代码:
import inspect
def f(s):
print(" " * (len(inspect.stack())-2), '>>', s)
if len(s) <= 1:
print( " " * (len(inspect.stack())-2), '<<', s)
return s
else:
retval = f(f(s[1:])) + s[0] #Note double recursion
print( " " * (len(inspect.stack())-2), '<<', retval)
return retval
print(f('world'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句