0% found this document useful (0 votes)
5 views29 pages

Unit 5

The document discusses iterators and recursion in Python. It explains what iterators are, how they work, and provides examples of using iterators with strings, tuples, and lists. It also explains recursion with examples of recursive functions to calculate Fibonacci numbers and solve the Tower of Hanoi problem. The document then covers various searching and sorting algorithms like linear search, binary search, selection sort, merge sort.

Uploaded by

swatisha3011
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)
5 views29 pages

Unit 5

The document discusses iterators and recursion in Python. It explains what iterators are, how they work, and provides examples of using iterators with strings, tuples, and lists. It also explains recursion with examples of recursive functions to calculate Fibonacci numbers and solve the Tower of Hanoi problem. The document then covers various searching and sorting algorithms like linear search, binary search, selection sort, merge sort.

Uploaded by

swatisha3011
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/ 29

Unit V

By
Dr.Arvinda kushwaha
Professor and Head of Department
Department of Computer Sc.& Engineering
MIET, Meerut ,(068)
Course Outline
Iterators & Recursion
Time Sorting & Merging
Prop
U osed
Topic
nit Lect
ure

Iterators & Recursion: Recursive Fibonacci , Tower Of Hanoi Search : Simple


Search and Estimating Search Time , Binary Search and Estimating Binary
V 08
Search Time Sorting & Merging: Selection Sort , Merge List , Merge Sort ,
Higher Order Sort
Iteration
4

Python Iterators
An iterator is an object that contains a countable
number of values.
An iterator is an object that can be iterated upon,
meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which
implements the iterator protocol, which consist of the
methods __iter__() and __next__().
Iterator vs Iterable
5

Lists, tuples, dictionaries, and sets are all iterable objects.


They are iterable containers which you can get an iterator
from.
All these objects have a iter() method which is used to get
an iterator:
Example:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Conti….
6

Strings are also iterable objects, containing a sequence of


characters:
Example:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Conti….
7
Looping Through an Iterator
We can also use a for loop to iterate through an
iterable object:
Example:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
#Iterate the characters of a string:
mystr = "banana"
for x in mystr:
print(x)
Recursion in python
8

Python also accepts function recursion, which means


a defined function can call itself.
Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.
Conti….
9

Example 1:
def recursion1(n):
if(n>0):
result = n+recursion1(n-1)
print(result)
else:
result = 0
return result

print("\nRecursion Example Results")


recursion1(6)
Conti…
10

Example 2:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input(“enter the number”))
print(factorial(num))
Advantages of Recursion
11

Recursive functions make the code look clean and


elegant.
A complex task can be broken down into simpler
sub-problems using recursion.
Sequence generation is easier with recursion than
using some nested iteration.
Disadvantages of Recursion
12

Sometimes the logic behind recursion is hard to


follow through.
Recursive calls are expensive (inefficient) as they
take up a lot of memory and time.
Fibonacci series:
13

n = int(input(“enter number”))
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
for i in range(n)
Print(recur_fibo(i))
Tower of Hanoi
14

def TowerOfHanoi(n , source, destination, auxiliary):


if n==1:
print ("Move disk 1 from source",source,"to
destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to
destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n=3
TowerOfHanoi(n,'A','B','C')
Linear Search (Simple Search):
15

In linear search, we access each element one by one


sequentially and see whether it is desired element or
not. A search will be unsuccessful if all the elements
are accessed, and the desired element is not found.
Linear search program:
16

a={}
for i in range(0,8):
a[i]=eval(input("Enterno."))
no=eval(input("Enter no. tosearch:"))
for i in range(0,8):
if a[i] == no:
flag = 1
break
if flag == 1:
print("no.isavailableinlist")
else:
print("no.isnotavailableinlist")
Binary search:
17

Binary search is a techniques of searching data in sorted list.


This technique Searches the data in minimum possible
comparisons. The logic behind this technique is given below:
First find the middle elements of the array compare the mid((first
+ last)/2) element with an item (either left or right)
If it is less than desired element, then search only the first half of
the array.
If it is greater than the desired element search in the second half
of the array.
Repeat the same steps until search is compete.
Binary search program:
18 def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
Conti….
19

arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, x)

if result != -1:
print("Element is present at index”, str(result))
else:
print("Element is not present in array")
Selection sort
20

In this algorithm, we select the smallest element from


an unsorted array in each pass and swap with the
beginning of the unsorted array.
This process will continue until all the elements are
placed at right place.
It is simple and an in-place comparison sorting
algorithm.
Hence the time complexity of merge sort algorithm is
O(n2).
Selection sort:
21

import sys # Swap the found minimum element


with
A = [64, 25, 12, 22, 11]
# the first element
# Traverse through all array elements A[i], A[min_idx] = A[min_idx], A[i]
for i in range(len(A)):
# Driver code to test above
# Find the minimum element in print ("Sorted array")
remaining for i in range(len(A)):
# unsorted array print("%d" %A[i]),

min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
Join / Merge lists ( two or more)
22

Join / Merge two lists in python using + operator:


Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
final_list = list_1 + list_2
print(final_list)
Conti….
23

Join / Merge two lists in python using list.extend():


Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
list_1.extend(list_2)
print(list_1)
Conti…..
24

Join / Merge two lists in python using for loop:


Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
for elem in list_2:
list_1.append(elem)
print(list_1)
Conti….
25

Join / Merge multiple lists using + operator:


Example:
list_1 = ["This" , "is", "a", "sample", "program"]
list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
list_3 = [11, 12, 13]
merged_list = list_1 + list_2 + list_3
print(merged_list)
Merge sort:
26

Merge sort is one of the most


prominent divide-and-conquer sorting algorithms in
the modern era.
It can be used to sort the values in any traversable
data structure such as a list.
Merge sort works by splitting the input list into two
halves, repeating the process on those halves, and
finally merging the two sorted halves together.
Conti….
27

def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
Conti….
28

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


if left[i] <= right[j]:
myList[k] = left[i]
i += 1
else:
myList[k] = right[j]
j += 1
k += 1
Conti….
29

while i < len(left):


myList[k] = left[i]
i += 1
k += 1
while j < len(right):
myList[k]=right[j]
j += 1
k += 1
myList = [54,26,93,17,77,31,44,55,20]
mergeSort(myList)
print(myList)

You might also like