What is a Recursive Call?
Recursion refers to a function calling itself.
This technique is commonly used to define mathematical functions such as factorials and Fibonacci sequences.
def factorial(n): if n == 0: # Base case return 1 # Recursion ends else: # Recursive call return n * factorial(n-1) # Calls itself with n-1 as argument # Example: Calculating factorial of 5 factorial_result = factorial(5) print("factorial_result:", factorial_result) # factorial_result: 120
Recursive functions are useful for solving complex problems by breaking them down into simpler, repetitive tasks.
Base Case
Every recursive function requires a termination condition, called the base case. It defines when the recursion stops.
For instance, in the factorial function above, the statement if n == 0 is the base case that ends the recursion.
This condition ensures that when n reaches 0, the function stops calling itself, preventing infinite recursion.
Pros and Cons of Recursion
Pros:
-
Simplifies code, making it more readable and intuitive.
-
It allows complex problems to be expressed concisely.
-
It is particularly useful for implementing data structures like trees and graphs.
Cons:
-
Recursive calls require additional memory, which can lead to higher usage.
-
If not implemented correctly, it can lead to infinite loops.
Lessons in this chapter · Practical Python Algorithms
- 1. Advanced Python Algorithms
- 2. What is a Recursive Call?
- 3. Implementing Fibonacci Sequence with Recursive Function
- 4. Fill-in-the-blank quiz
- 5. Coding Quiz - Fibonacci Sequence
- 6. Dynamic Programming and Divide and Conquer
- 7. Implementing Dynamic Programming in Python
- 8. Multiple-choice quiz
- 9. Coding Quiz - Make One
- 10. What is Merge Sort?
- 11. Implementing Merge Sort
- 12. Multiple-choice quiz
- 13. Coding Quiz - Sort a List Using Merge Sort
- 14. What is Quick Sort?
- 15. Implementing Quick Sort in Python
- 16. Multiple-choice quiz
- 17. Coding Quiz - Sort a List Using Quick Sort
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help