Unit 5
Unit 5
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
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
Example 1:
def recursion1(n):
if(n>0):
result = n+recursion1(n-1)
print(result)
else:
result = 0
return result
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
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
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
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
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
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