Python Ktu
Python Ktu
Page 1
Module 2
Page 2
Recursion
4
Page 3
What is Recursion?
► This process continues until the problem is reduced to a base case—a condition where
the recursion stops.
Page 4
Anatomy of a Recursive Function
Page 5
Key Components of Recursion
► Base Case: The base case is critical as it ensures that the recursion
terminates.
► Without it, the function will keep calling itself indefinitely, causing a stack
overflow.
def countdown(n):
if n == 0: # Base case
print("Blastoff!")
else:
print(n)
countdown(n - 1) # Recursive call
Page 6
Key Components of Recursion
► Progress Toward the Base Case: Each recursive call must reduce the size or
complexity of the problem, moving it closer to the base case.
def sum_numbers(n):
if n == 0: # Base case
return 0
else:
return n + sum_numbers(n - 1) # Progressing towards base case
Page 7
The Call Stack
► A stack is a data structure that follows the LIFO (Last In, First Out) principle
► The last item added to the stack is the first item removed.
► Push 10 → Stack: [10]
► Push 20 → Stack: [10, 20]
► Pop → Removes 20 → Stack: [10]
Page 8
The Call Stack
Page 9
How the Stack Works in Recursion
def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
Page 10
How the Stack Works in Recursion
Page 11
How the Stack Works in Recursion
Page 12
How the Stack Works in Recursion
Page 13
How the Stack Works in Recursion
Page 14
How the Stack Works in Recursion
Page 15
Recursion tree for 4!.
Page 16
Avoiding Circularity in Recursion
► Circularity in recursion occurs when the function lacks a clear base case or
fails to progress toward it, leading to infinite recursive calls and eventual
stack overflow.
► To avoid circularity:
► Always Define a Base Case: Ensure there's a condition to terminate recursion. For
example, in a factorial function, the base case is when n == 1.
► Progress Toward the Base Case: Ensure that each recursive call moves the problem
closer to the base case. For instance, decrementing n in factorial(n - 1) ensures
progress.
► Test Your Function Thoroughly: Check edge cases to verify that the base case is
reached under all conditions.
Page 17
Avoiding Circularity in Recursion
def bad_recursion(n):
print(n)
bad_recursion(n) # No base case, leads to infinite recursion.
def good_recursion(n):
if n == 0: # Base case
print("Done!")
else:
print(n)
good_recursion(n - 1) # Moves closer to the base case.
Page 18
Exercises
Page 19
Exercises
def find_max_recursive(numbers):
if len(numbers) == 1:
return numbers[0]
check only one element within list
else:
max_of_rest = find_max_recursive(numbers[1:])
return numbers[0] if numbers[0] > max_of_rest else max_of_rest
numbers = [3, 1, 4, 1, 5]
print("The maximum element is:", find_max_recursive(numbers))
Page 20
Exercises
def find_max_recursive(numbers):
if len(numbers) == 1:
return numbers[0]
else:
max_of_rest = find_max_recursive(numbers[1:])
return numbers[0] if numbers[0] > max_of_rest else max_of_rest
numbers = [3, 1, 4, 1, 5]
print("The maximum element is:", find_max_recursive(numbers))
Page 21
Reversing a String
def reverse_string_recursive(s):
# Base case: If the string is empty or has one character, it is already reversed
if len(s) <= 1:
return s
else:
# Recursive case: Reverse the rest of the string and append the first character
return reverse_string_recursive(s[1:]) + s[0] ello +h
llo+ e
lo+l
# Example usage o+l
input_string = "recursion" o ===
olleh
reversed_string = reverse_string_recursive(input_string)
print("Original String:", input_string)
print("Reversed String:", reversed_string)
Page 22
Reversing a String
def reverse_string_recursive(s):
# Base case: If the string is empty or has one character, it is already reversed
if len(s) <= 1:
return s
else:
# Recursive case: Reverse the rest of the string and append the first character
return reverse_string_recursive(s[1:]) + s[0]
# Example usage
numbers = [1, 2, 3, 2, 4, 2, 5]
target_value = 2
count = count_occurrences(numbers, target_value)
print(f"The value {target_value} appears {count} times in the list.")
Page 24
Counting the Occurrences of a Value in a List
lst[0] == Returned
Call Level Function Call lst Count
value Value
count_occurrences([1, 2, 3, 2, 4, 2],
1 [1, 2, 3, 2, 4, 2] False 0
2)
Page 25
Counting the Occurrences of a Value in a List
Page 26
Difference Between Iteration and Recursion
Page 27
Difference Between Iteration and Recursion
Page 28
Reasons for using Recursion
Page 29
Reasons for using Recursion
Page 30