Examples of Recursion in Python
1. Sum of Natural Numbers
def sum_of_natural_numbers(n):
# Base case
if n == 0:
return 0
# Recursive case
return n + sum_of_natural_numbers(n - 1)
print(sum_of_natural_numbers(10)) # Output: 55
2. Power Calculation (Exponentiation)
def power(base, exp):
# Base case
if exp == 0:
return 1
# Recursive case
return base * power(base, exp - 1)
print(power(2, 3)) # Output: 8
3. Reversing a String
def reverse_string(s):
# Base case
if len(s) == 0:
return ""
# Recursive case
return s[-1] + reverse_string(s[:-1])
print(reverse_string("hello")) # Output: "olleh"
4. Find the Greatest Common Divisor (GCD)
def gcd(a, b):
# Base case
if b == 0:
return a
# Recursive case
return gcd(b, a % b)
print(gcd(48, 18)) # Output: 6
5. Tower of Hanoi
def tower_of_hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, target, source)
tower_of_hanoi(3, 'A', 'C', 'B')
6. Binary Search
def binary_search(arr, target, low, high):
# Base case
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, low, mid - 1)
else:
return binary_search(arr, target, mid + 1, high)
arr = [1, 3, 5, 7, 9, 11]
print(binary_search(arr, 7, 0, len(arr) - 1)) # Output: 3
7. Flatten a Nested List
def flatten_list(nested_list):
# Base case
if not nested_list:
return []
if isinstance(nested_list[0], list):
# Recursive case for nested list
return flatten_list(nested_list[0]) + flatten_list(nested_list[1:])
else:
# Recursive case for non-nested elements
return [nested_list[0]] + flatten_list(nested_list[1:])
nested_list = [1, [2, [3, 4], 5], 6]
print(flatten_list(nested_list)) # Output: [1, 2, 3, 4, 5, 6]
8. Check if a Number is Palindromic
def is_palindrome(s):
# Base case
if len(s) <= 1:
return True
# Recursive case
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
9. Count Ways to Climb Stairs
def climb_stairs(n):
# Base cases
if n == 1:
return 1
if n == 2:
return 2
# Recursive case
return climb_stairs(n - 1) + climb_stairs(n - 2)
print(climb_stairs(5)) # Output: 8
10. Generate Permutations
def permutations(s):
# Base case
if len(s) == 1:
return [s]
# Recursive case
result = []
for i, char in enumerate(s):
for perm in permutations(s[:i] + s[i+1:]):
result.append(char + perm)
return result
print(permutations("abc")) # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']