How to clear python recursion? -
i'm pretty new python , have few question recursion error: "runtimeerror: maximum recursion depth exceeded". know error in python avoid stack overflow. have made example code here:
import sys def print1(): print("1") return print2() def print2(): print("2") return print3() ------------- def print3() - def print7() <- (wrote here save place) ------------- def print8(): print("8") return print9() def print9(): print("9") def main(): sys.setrecursionlimit(11) print sys.getrecursionlimit() print1() if __name__ == "__main__": main()
now if have set recursion limit 11, code run, there no errors. output:
11 1 2 3 4 5 6 7 8 9
if set recursion limit 10, there error:
10 1 2 3 4 5 6 7 8 traceback (most recent call last): file "nimetu1.py", line 44, in <module> main() file "nimetu1.py", line 41, in main print1() file "nimetu1.py", line 5, in print1 return print2() file "nimetu1.py", line 9, in print2 return print3() file "nimetu1.py", line 13, in print3 return print4() file "nimetu1.py", line 17, in print4 return print5() file "nimetu1.py", line 21, in print5 return print6() file "nimetu1.py", line 25, in print6 return print7() file "nimetu1.py", line 29, in print7 return print8() file "nimetu1.py", line 33, in print8 return print9() runtimeerror: maximum recursion depth exceeded
my question is, there solution clear recursion or other solution, how write code similar this, 1 function calls , there no need last function, current function called. example clear recursion @ print2() , run code recursion limit @ 10. want write code function calling function, save ram think need alternative or other solution. code may call same function many times too.. there may later 3 different same function blocks running, thats want avoid.
make loop calls whatever thunk returned:
def main(): todo = print1 while todo: todo = todo()
print1
returns call next without calling it:
def print1(): print("1") return print2
the thing need stop return false
instead of next function call.
the stack rewound each call , never accumulated.
Comments
Post a Comment