Lesson 11/25 ยท ๐ Recursion
๐ RecursionLesson 11/25
Phase 3 ยท Recursion20 min
Recursion Fundamentals
Functions that call themselves, and why that's not as scary as it sounds
Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive solution has two parts:
1. Base case, the simplest version that doesn't recurse (stops infinite loops)2. Recursive case, breaks the problem into a smaller version of itself
1. Base case, the simplest version that doesn't recurse (stops infinite loops)2. Recursive case, breaks the problem into a smaller version of itself
Classic recursion: factorialpython
def factorial(n):
# Base case: 0! = 1
if n == 0:
return 1
# Recursive case: n! = n ร (n-1)!
return n * factorial(n - 1)
# factorial(4) = 4 ร factorial(3)
# = 4 ร 3 ร factorial(2)
# = 4 ร 3 ร 2 ร factorial(1)
# = 4 ร 3 ร 2 ร 1 ร factorial(0)
# = 4 ร 3 ร 2 ร 1 ร 1
# = 24
print(factorial(4)) # โ 24๐Code TracerStep 1 / 5
trace.py
1def fib(n):
2 if n <= 1: return nโ
3 return fib(n-1) + fib(n-2)
4
5result = fib(4)
Variables
nint
4Step 1 / 5
๐คQuick Check
What happens if you forget the base case in a recursive function?
Practice Exercises
0/1 solvedExercise 1 of 1medium
โฑ 00:00Power Function
Implement x raised to the power n using recursion. Use fast exponentiation (halve the problem each time).
Expected output:
Expected output:
8solution.py
1 / 1
Solve all 1 exercise to unlock completion