Recursive Functions in Python
A. What is Recursion?
Recursion is a functions or methods that calls itself. Recursion functions are reused. Its general goal is to solve complex problems and reduce the time complexity.
Recursion syntax:
B. Why Is It Important?
using recursive functions is generally easier than using ‘for’ or ‘while’ loops. Reduce the Time complexity. Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach.
A recursive function consists of two parts: the recursive call and the base case.
The base case: It is the mechanism that stops this process of ever more recursive calls and an ever-growing stack of function calls waiting on the return of other function calls. Every recursive function should have at least one base case, though there may be multiple.
The recursive call: is the condition, when the function calls itself, adding to the recursive call stack.
C. When to use?
Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach.
For example, searching through a file system. You could start at the root folder, and then you could search through all the files and folders within that one. After that, you would enter each folder and search through each folder inside of that.
D. Examples:
In this article, I have included some basic examples that will provide a better understanding of the recursion functions. Many math functions such as the factorial or the sum of all previous numbers are good examples of this.
1. Factorial of the number:
Factorial of the 5! is 5 * 4 * 3 * 2 * 1 is 120
2. sum of all previous numbers:
The above recursive function called sum will add the values from the 7 till 0, that is 7 + 6 + 5+ 4 + 3 + 2+ 1 = 28
3. Create a recursive function that computers the powers of a number using the following equation:
The function calculates given math function output for 2^3 is 8
E. Advantage and Disadvantage of Recursion:
Advantage:
Disadvantage:
| Ph.D. Candidate | Instructional Design & Technology | EdTech | Accessibility | Training | Change Agent | Lifelong Learner | First Gen Education Advocate | Coach |
3ySonali, thank you for sharing this learning experience! I am looking forward to reading more of your work as we continue this year with The Knowledge House.