Data Structures & Algorithms in Python – Recursion

Recursion is a programming technique in which a function calls itself.

It works similar to a loop in which the code gets executed over and over again. Thus, it is important that we set up a condition to determine when the recursive call should end.

The condition that terminate the function or ends the recursive call is also known as base case.

In order to stop a recursive function from running infinitely, the function requires a base case.

Recursive Functions in Python

Let’s use a common example of recursion, which is to calculate the factorial of an integer.

“!” after an integer denotes the notation of a factorial. For example:

5! = 5 * 4 * 3 * 2 * 1

Our program will break down the problem into smaller pieces and solve it. Here is a simple implementation:

def factorial(number):
    if n == 0: #This is the base case of this function.
        return 1
    else:
        return n * factorial(number-1) #Function calling itself.

print(factorial(5))

The expected output of the above code will be:

120

Here is another example of recursion in Python:

def count(number):
  print(number)
  number = number + 1
  count(number)
  

Can you guess what is the problem in the above code?

Well, there is no base case to terminate the function. This recursive function will run infinitely.

Ultimately causing the program to crash.

Final Thoughts on Recursion

Recursion can be used to solve complicated problems. As it can break down a problem into smaller chunks which makes the problem easier to solve and visualize.

The reduction of time complexity is one of the reasons why recursion is used often times, instead of loops.

However, do know that recursion or a recursive function requires more memory.

Sometimes using a loop might be more efficient for your program rather than a recursive function.

If you have any comments or concern, feel free to let me know below. I also recommend checking out other guides about Python on my blog.

Leave a Reply