11+ Python Recursion Practice Problems With Solutions - Python Mania
11+ Python Recursion Practice Problems With Solutions - Python Mania
This tutorial will cover some Python Recursion Practice Problems With
Solutions.
Solution
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
120
Solution
def reverse_string(s):
if len(s) == 0:
return s
else:
return reverse_string(s[1:]) + s[0]
Output
PYTHON MANIA
Here’s a recursive function that finds the GCD of two numbers using the
Euclidean algorithm:
Solution
a = 32
b = 120
result = gcd(a, b)
print(result)
Output
Solution
def sum_list(lst):
if len(lst) == 0:
return 0
else:
return lst[0] + sum_list(lst[1:])
Output
34
def is_palindrome(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and is_palindrome(s[1:-1])
result = is_palindrome("543212345")
print(result)
Output
True
Solution
Here’s a recursive function that takes a list of numbers and returns the
smallest value:
def min_value(lst):
if len(lst) == 1:
return lst[0]
else:
return min(lst[0], min_value(lst[1:]))
#Pass any string to this function
#It will return the minimum entry of the list
#Let's pass a string and check whether its working or not
Output
You can see, 3 is the minimum number that is present in the list
Solution
base = 2
exponent = 3
result = power(base, exponent)
print(result)
Output
Related Articles:
Python Program for Matrix Addition with User Input (With Code)
Recent Articles:
0
Article Rating
0 COMMENTS
Related Tutorials:
PYTHON MANIA