Sobes.tech
Middle

What is tail recursion?

sobes.tech AI

Answer from AI

Tail recursion is a special type of recursion where the recursive call is the last operation in the function body.

Advantages:

  • Optimization: The compiler can transform the tail-recursive call into a regular loop, avoiding call stack growth.
  • Avoiding stack overflow: Allows very deep recursive calls to be performed without the risk of a Stack Overflow Error.

Example of a non-optimized factorial function:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1) # Recursive call is not the last operation

Example of an optimized tail-recursive factorial function:

def factorial_tail(n, accumulator=1):
    if n == 0:
        return accumulator
    else:
        return factorial_tail(n - 1, accumulator * n) # Recursive call is the last operation

It is important to note that in CPython (the standard Python implementation), tail recursion optimization is not automatic. To gain the benefits, you need to use alternative Python implementations (such as PyPy) or apply iterative approaches.