Advanced Patterns in Python: Example 1

Example 1: The "I'm-Too-Much-of-A-Problem

Imagine a scenario where you're trying to solve a simple problem, but your Python script is getting bogged down in an infinite loop of recursion.

You're like:


def recursive_function(n):
  print(n)
  recursive_function(n-1)

recursive_function(10)
      

But, you're getting:


10
9
8
7
6
5
4
3
2
1
... (infinite loop of recursion)
      

What's happening here is that the function is calling itself, creating an unending chain of calls. To break this cycle, you can use a technique called "tail recursion optimization."

Let's take a look at how to implement this optimization in Python:

Learn about tail recursion optimization