0% found this document useful (0 votes)
15 views5 pages

W9PPS2

The document covers advanced concepts of recursion in Python, including basic recursive functions like factorial and Fibonacci, as well as applications in divide and conquer strategies such as merge sort and binary search. It provides code examples for various recursive problems, including the Tower of Hanoi and calculating GCD. The conclusion emphasizes the utility of recursion for specific problems and compares it with iterative approaches.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

W9PPS2

The document covers advanced concepts of recursion in Python, including basic recursive functions like factorial and Fibonacci, as well as applications in divide and conquer strategies such as merge sort and binary search. It provides code examples for various recursive problems, including the Tower of Hanoi and calculating GCD. The conclusion emphasizes the utility of recursion for specific problems and compares it with iterative approaches.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Week 9: Python Functions-II

Recursion
Introduction to Recursion

Recursion is a programming technique where a function calls itself to solve a problem. A recursive function
must have a base condition to avoid infinite loops.

Basic Recursive Function

Example: Factorial Calculation

def factorial(n):
if n == 0 or n == 1:
return 1 # Base condition
return n * factorial(n - 1) # Recursive call

print(factorial(5)) # Output: 120

Understanding Recursive Calls

Each function call is added to the call stack and executed in reverse order upon reaching the base condition.

Fibonacci Series Using Recursion


def fibonacci(n):
if n <= 0:
return "Invalid input"
elif n == 1:
return 0
elif n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6)) # Output: 5

Divide and Conquer Using Recursion and Iteration


Introduction to Divide and Conquer

Divide and Conquer is a problem-solving approach where:

1. A problem is broken into smaller subproblems.


2. Each subproblem is solved recursively or iteratively.
3. Solutions are combined to solve the original problem.

Merge Sort Using Recursion


def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
sorted_arr = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_arr.append(left[i])
i += 1
else:
sorted_arr.append(right[j])
j += 1
sorted_arr.extend(left[i:])
sorted_arr.extend(right[j:])
return sorted_arr

print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # Output: Sorted array

Binary Search Using Recursion and Iteration

Recursive Approach:

def binary_search_recursive(arr, target, low, high):


if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search_recursive(arr, target, low, mid - 1)
else:
return binary_search_recursive(arr, target, mid + 1, high)

arr = [1, 3, 5, 7, 9, 11]


target = 7
print(binary_search_recursive(arr, target, 0, len(arr) - 1)) # Output: Index of 7

Iterative Approach:

def binary_search_iterative(arr, target):


low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

print(binary_search_iterative(arr, target)) # Output: Index of 7

Additional Examples

Tower of Hanoi Problem (Recursion)

def tower_of_hanoi(n, source, auxiliary, target):


if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)

tower_of_hanoi(3, 'A', 'B', 'C')


Greatest Common Divisor (GCD) Using Recursion

def gcd(a, b):


if b == 0:
return a
return gcd(b, a % b)

print(gcd(48, 18)) # Output: 6

Conclusion
 Recursion is useful for problems like factorial, Fibonacci, and tree traversals.
 Divide and Conquer optimizes sorting and searching operations.
 Iteration is often more space-efficient compared to recursion.

This concludes the lesson on recursion and divide-and-conquer techniques.

Practice:

1. Factorial of a Number

Write a recursive function to calculate the factorial of a given number n.

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120

2. Fibonacci Series (Nth Term)

Write a recursive function to find the Nth Fibonacci number.

def fibonacci(n):
if n <= 0:
return "Invalid input"
if n == 1:
return 0
if n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 5

3. Sum of Natural Numbers

Write a recursive function to find the sum of the first N natural numbers.

def sum_n(n):
if n == 0:
return 0
return n + sum_n(n - 1)
print(sum_n(5)) # Output: 15 (1+2+3+4+5)
4. Reverse a String

Write a recursive function to reverse a given string.

def reverse_string(s):
if len(s) == 0:
return s
return s[-1] + reverse_string(s[:-1])
print(reverse_string("hello")) # Output: "olleh"

5. Check if a Number is Palindrome

Write a recursive function to check if a number is a palindrome.

def is_palindrome(n, rev=0):


if n == 0:
return rev
rev = rev * 10 + n % 10
return is_palindrome(n // 10, rev)

num = 121print(is_palindrome(num) == num) # Output: True

6. Power Function (a^b)

Write a recursive function to calculate a^b.

def power(a, b):


if b == 0:
return 1
return a * power(a, b - 1)
print(power(2, 3)) # Output: 8

7. Greatest Common Divisor (GCD)

Write a recursive function to find the GCD of two numbers using the Euclidean algorithm.

def gcd(a, b):


if b == 0:
return a
return gcd(b, a % b)
print(gcd(48, 18)) # Output: 6

8. Binary Search (Recursive)

Write a recursive function to implement binary search.

def binary_search(arr, low, high, target):


if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, low, mid - 1, target)
else:
return binary_search(arr, mid + 1, high, target)

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(binary_search(arr, 0, len(arr) - 1, 5)) # Output: 4

9. Tower of Hanoi

Write a recursive function to solve the Tower of Hanoi problem.

def tower_of_hanoi(n, source, auxiliary, destination):


if n == 1:
print(f"Move disk 1 from {source} to {destination}")
return
tower_of_hanoi(n - 1, source, destination, auxiliary)
print(f"Move disk {n} from {source} to {destination}")
tower_of_hanoi(n - 1, auxiliary, source, destination)

tower_of_hanoi(3, 'A', 'B', 'C')

10. Sum of Digits of a Number

Write a recursive function to find the sum of the digits of a number.

def sum_of_digits(n):
if n == 0:

return 0
return n % 10 + sum_of_digits(n // 10)
print(sum_of_digits(1234)) # Output: 10 (1+2+3+4)

You might also like