关于递归的问题
请建议我解决以下问题
考虑一个函数
function recurse(a):
for child in a.childs:
recurse(child)
现在我想执行一些代码,比如说
print "Program ends here"
程序完成递归时,那么我如何知道递归何时结束?
谢谢
Please suggest me the solution to the following problem
consider a function
function recurse(a):
for child in a.childs:
recurse(child)
Now I want to execute some code lets say
print "Program ends here"
when the program is done with recursion,so how can I know when the recursion will end?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
到目前为止提出的各种答案,总结起来就是“在
recurse
之外进行”,都很好。但是,如果您热衷于内部递归
,那也不难(只是效率稍低):名称中的前导
_
_toplevel
参数表示它是私有的,因此调用者知道不传递它。类似的解决方案涉及跟踪递归的级别(不仅仅是它是否是顶级,而是一般来说“你有多深”):
虽然在其他情况下很珍贵(例如打印出嵌套结构 )缩进)这里不需要它(与我给出的基于
_toplevel
布尔值的第一个解决方案相比,还有另一个边际效率损失)。The various answers proposed so far, which sum up to "do it outside of
recurse
", are fine. But if you're keen to do it insiderecurse
, that's not hard either (just marginally less efficient):The leading
_
in the name of the_toplevel
argument indicates it's private, so callers know not to pass it.Similar solutions involve keeping track of the level of recursion (not just whether it's top level or not, but "how deep you are" in general):
While precious in other cases (e.g. printing out nested structures with indents) it's not needed here (and there's another marginal loss of efficiency compared with the first solution I gave, based on the
_toplevel
boolean).你的意思是这样吗?
递归函数完成后,程序将继续执行下一条语句,就像任何其他函数一样。该函数是递归的并不重要。
Do you mean like this?
When the recursive function is done, the program will continue with the next statement, just like with any other function. That the function was recursive doesn't matter.
您可以使用默认参数:
You could use a default parameter:
我可能误解了你的问题,但递归将在最高级别完成时完成。
包装 recurse() 的新函数可以执行此操作:
I may be misunderstanding your question, but the recursion will be done when the highest level completes.
A new function that wraps recurse() could do this:
将 print 语句放在第一次调用 recurse 之后。
Put the print statement after the first call to recurse.