views:

86

answers:

5

Hi,

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

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
Forrest
+2  A: 

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.

sth
A: 

Put the print statement after the first call to recurse.

def main():
    a = NodeOfSomeSort()
    recurse(a)
    print "Recursion done!"        
NorthIsUp
+3  A: 

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

Alex Martelli
+2  A: 

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)
Tim Schaeffer