Search code examples
pythonalgorithmrecursion

Better Ways to Control Against Infinite Recursion


I am wondering if there is a standard way or a better way to control against infinite recursion than in my code below? I want my recursive function to give up after max attempts. The code below does it by introducing attempt method parameter and incrementing it during the recursive invocation. Is there a better way?

def Rec(attempt=0):
    if attempt==10:
        return()
    else:
        print(attempt)
        Rec(attempt=attempt+1)

Rec()

Solution

  • Yours is already good. That's the way to go. It is good because it is light weight. You basically need an int and a condition branch - that's it.

    Alternatively you can try to guarantee to break the loop in the condition without a counter (but that usually is dependent from case to case).