DEV Community

Cover image for Programming In python - Recursion made easy
Eghosa Ordia
Eghosa Ordia

Posted on

Programming In python - Recursion made easy

Recursion in Python

Recursion is a programming technique used in Python where a function calls itself repeatedly until a certain condition is met. The recursive function breaks down a problem into smaller subproblems and calls itself for each of the subproblems. It comprises of a base case (also known as a terminal case) and a recursive case. The base case is the condition that the function must meet to stop calling itself, while the recursive case calls the function repeatedly until the base case is satisfied.

When a function calls itself within its own body, it creates a new instance of the function with a new set of parameters. This process continues until the base case is reached, at which point the function stops calling itself and returns the results.

An exemplary illustration of a recursive function is the factorial function:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
Enter fullscreen mode Exit fullscreen mode

In this instance, the factorial() function takes an integer n as input and returns its factorial. The base case is when n equals 1, and the function returns the final result.

Now, let us examine the function by analyzing each step of execution using an example factorial(5) which returns 120. When the function runs, the base case is not met as n (i.e., 5) does not equal 1. The function multiplies 5 by the function (i.e., the function calls itself), and this time n is 4 (which is 5-1). The function multiplies 4 by the function again with (4-1) as an argument, and the function calls itself repeatedly until the condition (2-1) is met, which equals 1. At this point, the function returns 1, and everything is multiplied out. The steps of the iteration are as follows:

1. 5 * factorial(4)
2. 4 * factorial(3)
3. 3 * factorial(2)
4. 2 * factorial(1)
5. 1 * 1 (because the base case was met and 1 is returned in that case)
Thus, the result of the function is 5 * 4 * 3 * 2 * 1 = 120

However, it is important to note that recursive functions can be slower and consume more memory than iterative functions, as each function call creates a new instance of the function on the call stack. Therefore, it is crucial to use recursion judiciously and consider optimizing your code for performance.

In conclusion, we have now gained a deeper understanding of recursion. Should you have any further inquiries or suggestions to enhance the quality of this post, please do not hesitate to share them in the comments section. Thank you.

Top comments (0)