Recursion
When a function call itself repeatedly , function is called recursive function and process in called recursion.
Direct recursion: When a function call itself directly from its body
def A():
A()
Indirect recursion: When a function call another function, which call its caller fuction
def A(): def B():
B() A():
Infinite recursion : When a function call itself repeatedly call again and again endlessly. It happens when base condition is not given or not reachable
One advantage and one disadvantage of recursion over iteration:
Advantage: Recursion makes code short and simple
Disadvantage: Recursion is slower then iteration due to overhead of multiple function calling and maintaining stack of it
#factorial using recursion
def fact(x):
def fact(x):
if(x==1):
return 1
else:
return x*fact(x-1)
# sum of n natural numbers using
recursion function
def sum(n):
if(n<=1):
return n
else:
return n+sum(n-1)
n=int(input("enter a number"))
print("sum of n natural numbers",sum(n))
sum(6)
6+sum(5)
6+5+sum(4)
6+5+4+sum(3)
6+5+4+3+sum(2)
6+5+4+3+2+sum(1)
6+5+4+3+2+1
=21
#Calculate power of an input number using recursion
def power(x,n):
if(n==0):
return 1
else:
return x*power(x,n-1)
x=int (input("Enter value of x") )
n=int (input("Enter value of n") )
print(power(x,n))
#fibonacci
series using recursion
def febo(n):
if(n<=1):
return n
else:
return(febo(n-1)+febo(n-2))
n=int(input("how many terms required for
series"))
for i in range(n):
print(febo(i))
#sum of squares using recursion
def sum(n):
if n==1:
return 1
else:
return n**2+sum(n-1)
print(sum(5))
#binary search in a list
# values must be sort before binary search
def binarySearch(arr, low, high, x):
while low <= high:
mid = int((low + high)/2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
low = mid + 1
# If x is smaller, ignore right half
else:
high = mid - 1
else:
return -1
arr=[22,33,56,78,85,92,97]
pos=binarySearch(arr,0,6,78)
if(pos==-1):
print("item not found")
else:
print("item present at",pos)
# binary search using recursion
def binarySearch (arr, low, high, x):
else:
#binary search in a list
# values must be sort before binary search
def binarySearch(arr, low, high, x):
while low <= high:
mid = int((low + high)/2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
low = mid + 1
# If x is smaller, ignore right half
else:
high = mid - 1
else:
return -1
arr=[22,33,56,78,85,92,97]
pos=binarySearch(arr,0,6,78)
if(pos==-1):
print("item not found")
else:
print("item present at",pos)
# binary search using recursion
def binarySearch (arr, low, high, x):
if
high >=low :
mid
= int((low
+ high)/2)
if
arr[mid]==
x:
return
mid
elif arr[mid]>
x:
return
binarySearch(arr,
low, mid-1, x)
else:
return
binarySearch(arr,
mid+1, high, x)
else:
return
-1
Comments
Post a Comment