Recursion in Python Class 12

Teachers and Examiners (CBSESkillEduction) collaborated to create the Recursion in Python Class 12. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Recursion in Python Class 12

Recursion in Python

Python allows for the recursion of functions, which allows a defined function to call itself. A popular idea in mathematics and computer programming is recursion.

There are two types of Recursion in Python. Function calls itself directly form within its body is an example of direct recursion. However, if a function calls another function which calls its caller function from within its body is known as indirect recursion.

Example
Direct recursion
def a() :
a()

Indirect recursion
def a() :
b()

Recursion in Python Class 12

The Two Laws of Recursion

  1. Must have a base case – At least one basic requirement or condition must be met before the function can stop calling itself.
  2. Must move toward the base case – The recursive calls should progress so that each time they get closer to the initial requirements.

Advantages of using Recursion

1. Recursion can be used to break a complex function into smaller problems.
2. Recursion is more efficient at creating sequences than any nested iteration.
3. Recursive functions make the code appear straightforward and efficient.

Disadvantages of using Recursion

1. Recursive consume a lot of memory and time.
2. Debugging recursive functions can be difficult.

Recursion in Python Class 12

How recursion works in python

The function is called repeatedly through recursion from within the function. The repeated calls to the function are carried out by the recursive condition up until the base case is satisfied.

Factorial of a Number Using Recursion

def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)
f=factorial(5)
print (“factorial of 5 is “,f)

Output
factorial of 5 is 120

Fibonacci numbers Using Recursion

def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input(“enter a number”))
if n <= 0:
print(“Enter a positive Number”)
else:
print(“Fibonacci sequence:”)
for i in range(n):
print(fibonacci(i))

Output
enter a number10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Recursion in Python Class 12

Binary Search Using Recursion

def b_Search (arr, first, last, x):
if last >= first:
mid =int( first + (last – first)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return b_Search(arr, first, mid-1, x)
else:
return b_Search(arr, mid+1, last, x)
else:
return -1
arr = [ 1,3,5,6,7,8,10,13,14 ]
x = 10
result = b_Search(arr, 0, len(arr)-1, x)
if result != -1:
print (“Position of the Element is %d” % result)
else:
print (“Element not found”)

Output
Element is present at index 6
> 10

error: Content is protected !!