7 UDCS 2086553 S2.docx-1 PDF
7 UDCS 2086553 S2.docx-1 PDF
No: 2086553
University of Mumbai
Practical Journal of
By
University of Mumbai
Certificate
__________________ __________________
Head, Dept. of
Computer science
_________________
Examiner
Declaration
I state that the term work submitted here for the Course: Analysis
of Algorithms and Researching Computing has been the outcome of
my own studies, experimentation, and analysis and is per the
guidance that we received in the Semester I of MSc Computer
Science Programme during July to December 2019.
I undertake that this work has not been copied from anywhere nor
been submitted to anywhere else than for the credit of the above
referred Programme.
INDEX
Sr Topic Page No
No
.
1 Write a program to implement insertion sort and find the running time of the 5
algorithm.
2 Write a program to implement merge sot algorithm. Compare the time and memory 7
complexity.
10 Write a program to implement greedy set cover algorithm to solve set covering 25
Practical No:- 01
Problem statement:- Write a program to implement insertion sort and find the running time
of the algorithm.
Insertion Sort :-
Pseudocode:-
INSERTION-SORT(A)
Code:-
def insertionSort(alist):
Output:-
Practical No:- 02
Problem statement:- Write a program to implement merge sot algorithm. Compare the time
and memory complexity.
Merge Sort :-
Code:-
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
Output:-
Practical No:- 03
Code:-
(ii) permute-by-cyclic()
Output :-
(i) permute-by-sorting()
import random
def bogosort(a):
n = len(a)
while(is_sorted(a)== False):
shuffle(a)
def is_sorted(a):
n = len(a)
for i in range(0,n-1):
if(a[i]<a[i+1]):
return False
return True
def shuffle(a):
n = len(a)
for i in range(0,n):
r=random.randint(0,n-1)
a[i], a[r] = a[r], a[i]
a= [3,4,1,5,2]
bogosort(a)
print("Sorting")
for i in range(len(a)):
print("%d"%a[i])
Output:-
Practical No:- 04
UDCS MSc Part I [2019-2020] Page 11
Analysis of Algorithms and Researching Computing Seat
No: 2086553
Concept analysis:-
Code:-
def lcs(M, N, a, b):
if a == 0 or b == 0:
return 0;
elif M[a-1] == N[b-1]:
return 1 + lcs(M, N, a-1, b-1);
else:
return max(lcs(M, N, a, b-1), lcs(M, N, a-1, b));
M = "PMMTPB"
N = "MXTXPYB"
print ("Length of LCS is ", lcs(M , N, len(M), len(N)))
Output:-
Practical No:- 05
Huffman’s code:-
Psuedocode:-
HUFFMAN(C)
1 n = |C|
2Q=C
3 for i = 1 to n - 1
4 allocate a new node
5 z.left = x = EXTRACT-MIN(Q)
6 z.right = y = EXTRACT-MIN(Q)
7 z.freq= x:freq + y:freq
8 INSERT(Q,z)
9 return EXTRACT-MIN(Q) //return the root of the tree
Code:-
import heapq
from collections import defaultdict
def encode(frequency):
heap = [[weight, [symbol, '']] for symbol, weight in frequency.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return sorted(heapq.heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
huff = encode(frequency)
print ("Symbol".ljust(10) + "Weight".ljust(10) + "Huffman Code")
for p in huff:
print (p[0].ljust(10) + str(frequency[p[0]]).ljust(10) + p[1])
Output:-
Program No:-06
Kruskal’s algorithm:-
Pseudocode
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
else :
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
result =[]
i=0
e=0
self.graph = sorted(self.graph ,key=lambda item: item[2])
parent = [] ; rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V -1 :
u,v,w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent ,v)
if x != y:
e=e+1
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
Output:-
Practical No :- 07
Concept analysis:-
Dijkstrass’s algorithm:-
Pseudocode:-
DIJKSTRA(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2S=0
3 Q = G,V
4 while Q != 0
5 u = EXTRACT-MIN(Q)
6 S = S U {u}
8 RELAX(u,v,w)
Code:-
from collections import defaultdict
class Graph:
def minDistance(self,dist,queue):
min = float("Inf")
min_index = -1
for i in range(len(dist)):
if dist[i] < min and i in queue:
min = dist[i]
min_index = i
Output:-
Code:-
def gcdExtended(a, b, x, y):
if a == 0 :
x=0
y=1
return b
x1 = 1
y1 = 1 # To store results of recursive call
gcd = gcdExtended(b%a, a, x1, y1)
x = y1 - (b/a) * x1
y = x1
return gcd
x=1
y=1
a = 70
b = 58
g = gcdExtended(a, b, x, y)
print("gcd(", a , "," , b, ") = ", g)
print("Extended Form")
print(a ," * " ,x ," + " ,b ," * ", y, " = ", g)
Problem statement:- Write a program to verify (i) Euclid’s theorem (ii) Fermat’s theorem.
Code:-
Euclid’s theorem:-
def gcd(a,b):
if a==0:
return b
return gcd(b%a,a)
a=5
b=10
print("gcd(",a,",",b,")= ",gcd(a,b))
a=35
b=10
print("gcd(",a,",",b,")= ",gcd(a,b))
a=31
b=2
print("gcd(",a,",",b,")= ",gcd(a,b))
Output:-
def testSomeNumbers(limit, n) :
if (n < 3):
return
for a in range(1, limit + 1):
for b in range(a, limit + 1):
pow_sum = pow(a, n) + pow(b, n)
c = pow(pow_sum, 1.0 / n)
c_pow = pow(int(c), n)
if (c_pow == pow_sum):
print("Count example found")
return
print("No counter example within given range and data")
testSomeNumbers(3, 4)
Output:-
Problem statement:- Write a program to implement greedy set cover algorithm to solve set
covering problem.
Code:-
def set_cover(universe, subsets):
"""Find a family of subsets that covers the universal set"""
elements = set(e for s in subsets for e in s)
# Check the subsets cover the universe
if elements != universe:
return None
covered = set()
cover = []
# Greedily add the subsets with the most uncovered points
while covered != elements:
subset = max(subsets, key=lambda s: len(s - covered))
cover.append(subset)
covered |= subset
return cover
def main():
universe = set(range(1, 11))
subsets = [set([1, 2, 3, 8, 9, 10]),
set([1, 2, 3, 4, 5]),
set([4, 5, 7]),
set([5, 6, 7]),
set([6, 7, 8, 9, 10])]
cover = set_cover(universe, subsets)
print(cover)