开发者

Problem about recursion

Please suggest me the solution to the following problem

consider a function

function recurse(a):

  for child in a.childs:

      开发者_如何学Pythonrecurse(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


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 inside recurse, that's not hard either (just marginally less efficient):

function recurse(a, _toplevel=True):
  for child in a.childs:
      recurse(child, False)
  if _toplevel:
      print "Recursion done!"

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):

function recurse(a, _level=0):
  for child in a.childs:
      recurse(child, _level + 1)
  if _level == 0:
      print "Recursion done!"

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?

recurse(something)
print "Program ends here"

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:

function recurse(a, top=True):
    for child in a.childs:
        recurse(child, False)
    if top: print("Program ends here.")

recurse(a)


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:

function do_recursion(a):
    res = recurse(a)
    print "Program ends here"
    return res


Put the print statement after the first call to recurse.

def main():
    a = NodeOfSomeSort()
    recurse(a)
    print "Recursion done!"        
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜