RecursionError
in Python.# Recursive function to print numbers in descending order
def print_numbers(n):
if n == 0: # Base condition
return
else:
print(n)
print_numbers(n - 1)
# Calling the function
print_numbers(3)
Input: 3
Output:3
2
1
Explanation:print_numbers
reduces the value of n
by 1 in each call.n
equals 0 (the base condition).RecursionError: maximum recursion depth exceeded
For example:# Infinite recursion example
def infinite_recursion(n):
print(n)
infinite_recursion(n - 1)
# Calling the function
infinite_recursion(3)
Output: Numbers from 3
to -994
, followed by the above error message.n
natural numbers using recursion:# Recursive function to calculate the sum of natural numbers
def sum_of_natural_numbers(n):
if n == 0: # Base condition
return 0
else:
return n + sum_of_natural_numbers(n - 1)
# Calling the function
result = sum_of_natural_numbers(3)
print(result)
Output: 6
# Recursive function for factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the function
number = 5
print("Factorial of", number, "is", factorial(number))
Output: Factorial of 5 is 120
# Recursive function to check for palindrome
def is_palindrome(s):
if len(s) < 2: # Base condition
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
# Input from user
word = "madam"
if is_palindrome(word):
print("The string is a palindrome")
else:
print("The string is not a palindrome")
Output: The string is a palindrome
# Recursive function for GCD
def gcd(a, b):
if b == 0: # Base condition
return a
else:
return gcd(b, a % b)
# Input from user
a, b = 48, 18
print("GCD is:", gcd(a, b))
Output: GCD is: 6
RecursionError
.Q3: Can all problems be solved using recursion?
No, recursion is ideal for problems that can be divided into smaller sub-problems. For some cases, iterative solutions are more efficient.