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