Short Notes: Chapter 4 (Recursion) - Goodrich Python Book
4.1.1 - The Factorial Function
- The factorial of n (n!) is defined as:
n! = n * (n-1) * ... * 1, with 0! = 1
- Recursive definition:
n! = n * (n-1)!, for n > 0
- Base case: 0! = 1
- Common example to illustrate recursion.
4.1.3 - Binary Search
- Binary Search is a divide-and-conquer algorithm used on sorted sequences.
- Steps:
- Compare middle element to target.
- If equal -> return index.
- If smaller -> search right half.
- If larger -> search left half.
- Time Complexity: O(log n)
4.4.1 - Linear Recursion
- A recursive call that makes at most one recursive call per activation.
- Reduces problem size linearly.
- Example: sum of list elements:
def linear_sum(S, n):
if n == 0:
return 0
else:
Short Notes: Chapter 4 (Recursion) - Goodrich Python Book
return linear_sum(S, n-1) + S[n-1]
- Space Complexity: O(n)
4.4.2 - Binary Recursion
- Each call makes two recursive calls.
- Example: Fibonacci numbers:
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
- Time Complexity: O(2^n)
- Used when problems divide into two subproblems.