Recursion
17 July 2023 22:12
Python also accepts function recursion, a function can call itself is a recursion.
Recursion is common mathematical and programming concepts. It means that function
can call itself. This has the benefits of meaning that you can loop data until reaches the
results.
Programs:
Power of a number using recursion:
def power(a,b):
if b!=0:
return a*power(a,b-1)
else:
return 1
a=float(input())
b=float(input())
print(a,"to the power",b,"is", power(a,b))
Output:
4
4
4.0 to the power 4.0 is 256.0
Prime number using recursion:
def is_prime(n, i=2):
if n <= 2:
return n == 2
if n % i == 0:
return False
if i * i > n:
return True
return is_prime(n, i + 1)
n=float(input())
is_prime(n)
Output:
971
True
Largest element in an array using recursion in python:
def findmaxrec(a,n):
if(n==1):
return a[0]
return max(a[n-1], findmaxrec(a,n-1))
python intro Page 1
return max(a[n-1], findmaxrec(a,n-1))
if __name__=="__main__":
a=[1,4,45,6,-50,10,2]
n=len(a)
print(findmaxrec(a,n))
Output:
45
Smallest element in a array using recursion in python:
def findminrec(a,n):
if(n==1):
return a[0]
return min(a[n-1], findminrec(a,n-1))
if __name__=="__main__":
a=[4,8,9,45,54,-50,-100,55,44,65]
n=len(a)
print(findminrec(a,n))
Output:
-100
HCF of number using recursion:
def hcf(a,b):
if b==0:
return a
else:
return hcf(b,a%b)
a=int(input())
b=int(input())
print("hcf of" , a ,"and",b ,"is",hcf(b,a%b))
Output:
23
46
Hcf of 23 and 46 is 23
LCM of a number using recursion:
def hcf(a,b):
if b==0:
return a
else:
return hcf(b,a%b)
def lcm(a,b):
return(a*b)//hcf(a,b)
a=int(input())
b=int(input())
print("LCM of", a , "and", b ,"is ", hcf(b,a%b))
Output:
23
69
LCM of 23 and 69 is 69.
python intro Page 2
LCM of 23 and 69 is 69.
Calculate the length of the string using recursion:
def length(str):
if str == "":
return 0
return 1 + length(str[1:])
str = "prasanna"
print("The length of", str, "is", length(str))
Output:
The length of prasanna is 8
Factorial of the number using recursion:
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
num=int(input())
print("factorial of ", num , "is", factorial(num))
Output:
5
Factorial of 5 is 120
python intro Page 3