0% found this document useful (0 votes)
51 views17 pages

PYTHON UNIT-5 - (Notes-1)

The document discusses recursion, iteration, searching and sorting algorithms in Python. It explains recursion with examples like factorial and Fibonacci series. It also explains iteration with for and while loops. Linear search and binary search algorithms are described to search for elements in a list. Sorting algorithms like selection sort, insertion sort and merge sort are also covered with examples.

Uploaded by

Aman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views17 pages

PYTHON UNIT-5 - (Notes-1)

The document discusses recursion, iteration, searching and sorting algorithms in Python. It explains recursion with examples like factorial and Fibonacci series. It also explains iteration with for and while loops. Linear search and binary search algorithms are described to search for elements in a list. Sorting algorithms like selection sort, insertion sort and merge sort are also covered with examples.

Uploaded by

Aman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Python Programming

(KNC402)

Lecture Notes

(Unit-4)(Notes-1)(Iterators &
Recursion, Searching, Sorting and
Merging)
PYTHON PROGRAMMING UNIT-4

Recursion and Iteration


A computer program consists of line-by-line instructions. The computer performs those
instructions line-by-line. However, some instructions may be repetitive with a common
pattern. Recursion or iteration helps one to write a few lines of codes to perform such
repetitive tasks.
Recursion in Python
Recursion is a functional approach of breaking down a problem into a set of simple sub-
problems with an identical pattern and solving them by calling one sub-problem inside
another in sequential order. Recursion is executed by defining a function that can solve
one sub-problem at a time. Somewhere inside that function, it calls itself but solving
another sub-problem. Thus, the call to itself continues until some limiting criteria is
met.
The first call to a recursive function from the main program will be returned only after
all the sub-calls are finished. Hence, Python stores the results of all sub-problems in
temporary memory, executes some arithmetic operations (if needed), and releases the
memory after the end of recursion.
Iteration in Python
Iterations are performed through „for‟ and „while‟ loops. Iterations execute a set of
instructions repeatedly until some limiting criteria is met. In contrast to recursion,
iteration does not require temporary memory to keep on the results of each iteration.
Rather, programmers should define a variable (a number, or list, or string, or any
mutable data type) well before the start of iterative calls to collect the results (if there are
such arithmetic results) during each iteration.
Further, an iterative task can be accomplished by either a „for‟ loop or a „while‟ loop. A
„for‟ loop iterates over a sequence (such as a list, string, tuple and range). It terminates
the loop when there is no element left in the sequence. It automatically traverses through
the successive elements. But a „while‟ loop needs initialization of an iterator and manual
incrementation of the same. A „while‟ loop is executed until an iterator-based condition
is satisfied.
Example: Factorial of an Integer
Calculating factorial is a popular use case to understand iteration and recursion. For
instance, we wish to calculate the factorial of 10. It can be determined as
1*2*3*4*5*6*7*8*9*10 = 3628800. This can be viewed as 10 subproblems of
multiplying an incrementing integer to a final result.
# using iteration through for loop
n = 10
result = 1
for i in range(1,n+1):
result *= i
print(result)
Output:
3628800
PYTHON PROGRAMMING UNIT-4

A range function is implemented in a „for‟ loop since it requires a sequence to iterate


over. Range function supplies values iteratively from 1 through 10, one at a time. It stops
iteration when the range function stops supplying values (i.e., at 10).
# using iteration through while loop
n = 10
result = 1
i=1
while i <= n:
result *= i
i += 1
print(result)
Output:
3628800
In a „while‟ loop, an iterator i is introduced and incremented through every loop. While
loop stops iterating when the value of i exceeds the integer 10.

# using recursion
def Factorial(n):
# declare a base case (a limiting criteria)
if n == 1:
return 1
# continue with general case
else:
return n * Factorial(n-1)
print(Factorial(10))
Output:
3628800

A recursive function, named Factorial(), is defined with the limiting criteria of n=1. It
first attempts to find the factorial of 10. Factorial(10) is broken down into 10 *
Factorial(9). Further, Factorial(9) is broken down into 9 * Factorial(8), and so on. When
Factorial(1) is called, it stops the recursion. Factorial(10) awaits for the value of
Factorial(9). Factorial(9) awaits for the value of Factorial(8), and so on. Thus once the
limiting criteria (here, n=1) is reached, it starts returning the values.
PYTHON PROGRAMMING UNIT-4

Recursive Fibonacci:
1. Fibonacci series is a series of numbers formed by the addition of the preceding two
numbers in the series.
2. It is simply the series of numbers which starts from 0 and 1 and then continued by
the addition of the preceding two numbers.
3. Example of Fibonacci series: 0, 1, 1, 2, 3, 5.

# Program for recursive Fibonacci :


def FibRecursion(n) :
if n <= 1 :
return n
else :
return(FibRecursion(n-1) + FibRecursion(n-2))
nterms = int(input(“Enter the term : ”)) # take input from the user
if nterms <= 0: # check if the number is valid
print (“Please enter a positive integer”)
else :
print (“Fibonacci sequence:”)
for i in range (nterms) :
print(FibRecursion(i),end=” “)

#Output :
Enter the term : 5
Fibonacci sequence:
01123
PYTHON PROGRAMMING UNIT-4

Tower of Hanoi problem:


1. Tower of Hanoi is a mathematical puzzle which consists of three rods and a number
of disks of different sizes, which can slide onto any rod.
2. The puzzle starts with the disks in a neat stack in ascending order of size on one rod,
the smallest at the top, thus making a conical shape.
3. The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
a. Only one disk can be moved at a time.
b. Each move consists of taking the upper disk from one of the stack stand placing it on
top of another stack.
c. A disk can only be moved if it is the uppermost disk on a stack.
d. No disk may be placed on top of a smaller disk.

# Recursive Python function to solve Tower of Hanoi


def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n==1:
print (“Move disk 1 from rod”,from_rod,“to rod”,to_rod)
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print (“Move disk”,n,“from_rod”,from_rod,“to rod”,to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
n=4
TowerOfHanoi(n, "A","B","C")
# A, C, B are the names of rods
PYTHON PROGRAMMING UNIT-4

Output :
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
PYTHON PROGRAMMING UNIT-4

Searching Algorithm
When the data is stored in a machine and after a certain amount of time the same data is
to be retrieved by the user, the computer uses the searching algorithm to find the data.
The system jumps into its memory, processes the search of data using the searching
algorithm technique, and returns the data that the user requires. Therefore, the searching
algorithm is the set of procedures used to locate the specific data from the collection of
data.
Two of the searching algorithms are linear search and binary search.

Linear Search
Linear search is also known as a sequential searching algorithm to find the element
within the collection of data. The algorithm begins from the first element of the list,
starts checking every element until the expected element is found. If the element is not
found in the list, the algorithm traverses the whole list and return “element not found”.
Therefore, it is just a simple searching algorithm.
Example:
Consider the below array of elements. Now we have to find element a = 1 in the array
given below.

We will start with the first element of the array, compare the first element with the
element to be found. If the match is not found, we will jump to the next element of the
array and compare it with the element to be searched i.e „a‟.

If the element is found, we will return the index of that element else, we will return
'element not found'.
PYTHON PROGRAMMING UNIT-4

#Program for Linear Search


def LinearSearch(array, n, k):
for j in range(0, n):
if (array[j] == k):
return j
return -1
array = [1, 3, 5, 7, 9]
k=7
n = len(array)
result = LinearSearch(array, n, k)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)

Output:
Element found at index: 3

Time Complexity of Linear Search


The running time complexity of the linear search algorithm is O(n) for N number of
elements in the list as the algorithm has to travel through each and every element to find
the desired element.

Binary Search
Binary search is used with a similar concept, i.e to find the element from the list of
elements. Binary search algorithms are fast and effective in comparison to linear search
algorithms. The most important thing to note about binary search is that it works only on
sorted lists of elements. If the list is not sorted, then the algorithm first sorts the elements
using the sorting algorithm and then runs the binary search function to find the desired
output.
Example
Let the elements of array are -

Let the element to search is, K = 56


We have to use the below formula to calculate the mid of the array -
1. mid = (beg + end)/2
So, in the given array -
beg = 0
end = 8
mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.
PYTHON PROGRAMMING UNIT-4

Now, the element to search is found. So algorithm will return the index of the element
matched.
#Program for Binary Search (Iterative Method)
def binarySearch (arr, k, low, high):
while low <= high:
mid = (low + high)//2
if arr[mid] == k:
return mid
elif arr[mid] < k:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 3, 5, 7, 9]
k=5
result = binarySearch(arr, k, 0, len(arr)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

Output:
Element is present at index 2
PYTHON PROGRAMMING UNIT-4

#Program for Binary Search (Recursive Method)


def BinarySearch(arr, k, low, high):
if high >= low:
mid = (low + high)//2
if arr[mid] == k:
return mid
elif arr[mid] > k:
return BinarySearch(arr, k, low, mid-1)
else:
return BinarySearch(arr, k, mid + 1, high)
else:
return -1
arr = [1, 3, 5, 7, 9]
k=5
result = BinarySearch(arr, k, 0, len(arr)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

Output:
Element is present at index 2

Time complexity of Binary Search


The running time complexity for binary search is different for each scenario. The best-
case time complexity is O(1) which means the element is located at the mid-pointer. The
Average and Worst-Case time complexity is O(log n) which means the element to be
found is located either on the left side or on the right side of the mid pointer. Here, n
indicates the number of elements in the list.
PYTHON PROGRAMMING UNIT-4

Sorting and Merging


Arranging records in a particular sequence is a common requirement in data processing.
Such record sequencing can be accomplished using sort or merge operations.
 The sort operation accepts un-sequenced input and produces output in a specified
sequence.
 The merge operation compares two or more sequenced input and combines them in
sequential order.

What is Selection Sort?

Selection sort is a comparison sorting algorithm that is used to sort a random list of items in
ascending order. The comparison does not require a lot of extra space. It only requires one
extra memory space for the temporal variable.
This is known as in-place sorting. The selection sort has a time complexity of O(n2) where n
is the total number of items in the list. The time complexity measures the number of
iterations required to sort the list. The list is divided into two partitions: The first list contains
sorted items, while the second list contains unsorted items.
The unsorted list is then scanned for the minimum value, which is then placed in the sorted
list. This process is repeated until all the values have been compared and sorted.

Working of Selection Sort


1. Set the first element as minimum.

Select first element as minimum


2. Compare minimum with the second element. If the second element is smaller
than minimum, assign the second element as minimum.
Compare minimum with the third element. Again, if the third element is smaller,
then assign minimum to the third element otherwise do nothing. The process goes
on until the last element.

Compare minimum with the remaining elements


PYTHON PROGRAMMING UNIT-4

3. After each iteration, minimum is placed in the front of the unsorted list.

Swap the first with minimum


4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are
repeated until all the elements are placed at their correct positions.

The first iteration


PYTHON PROGRAMMING UNIT-4

The second iteration

The third iteration


PYTHON PROGRAMMING UNIT-4

The fourth iteration

# Program for Selection sort


def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

Output:
[-9, -2, 0, 11, 45]
PYTHON PROGRAMMING UNIT-4

What is Merge Sort?


The MergeSort function repeatedly divides the array into two halves until we reach a
stage where we try to perform MergeSort on a subarray of size 1 i.e. p == r.
After that, the merge function comes into play and combines the sorted arrays into larger
arrays until the whole array is merged.
In Merge Sort, a problem is divided into multiple sub-problems then each sub-problem is
solved individually. Finally, sub-problems are combined to form the final solution.

Merge Sort example


PYTHON PROGRAMMING UNIT-4

The merge Step of Merge Sort


Every recursive algorithm is dependent on a base case and the ability to combine the results
from base cases. The merge step is the solution to the simple problem of merging two sorted
lists (arrays) to build one large sorted list(array).

Merge step
PYTHON PROGRAMMING UNIT-4

# Program for MergeSort


def merge_sort(l):
if len(l)>1:
left=l[:len(l)//2]
right=l[len(l)//2:]

# Recursive call on each half


merge_sort(left)
merge_sort(right)

# Two iterators for traversing the two halves


i=0
j=0

# Iterator for the main list


k=0

while(i<len(left) and j<len(right)):


if left[i]<right[j]:
l[k]=left[i]
i+=1
else:
l[k]=right[j]
j+=1
k+=1

# For all the remaining values


while (i<len(left)):
l[k]=left[i]
i+=1
k+=1
while(j<len(right)):
l[k]=right[j]
j+=1
k+=1

l=[1,6,4,2,4,7,8,3,5,10]
merge_sort(l)
print(l)

Output:
[1, 2, 3, 4, 4, 5, 6, 7, 8, 10]

You might also like