20CSL57 - Ada Lab - 2018-22
20CSL57 - Ada Lab - 2018-22
ENGINEERING
LAB MANUAL
Course Outcomes: At the end of the Course, the Student will be able to
P P P P P P P P P PO PO PO
O O O O O O O O O 10 11 12
1 2 3 4 5 6 7 8 9
20CSL57 3 3 3 3 - - - - - 3 - 3
.1
20CSL57 3 3 3 3 2 - 2 - - 3 - 3
.2
20CSL57 3 3 3 3 - - 2 - - 3 - 3
.3
20CSL57 3 3 3 3 2 - - - - 3 - 3
.4
1. Continuous Assessment:
i) Will be carried out in every lab (for 12 labs -16 programs)
ii) Each program will be evaluated for 10 marks
iii) Totally for 16 lab programs it will be 160 marks. This will be scaled down to 10.
iv) During the semester, 2 internal tests will be conducted for 25 marks each. The total 50
marks for the internal tests will be scaled down to 15.
Not written 1
Answers correctly 2
2. Internal Test:
Break up of 25 marks (for each of the 2 internal tests) which is scaled down to 15marks
after the conduction of 2 internal tests:
The 1st lab internal will comprise of the first 5 lab programs and the 2nd lab internal will comprise
of the next 5 lab programs.
Not written 0
Session End Examination is conducted for 50 marks which is scaled down to 25 marks.
Not written 0
Exp. List of
No Experiments
1 Write a program to find GCD of two numbers using different algorithms
Write a program to Implement Sieve of Eratosthenes to generate Prime Numbers
2
Between Given Range
3 Write a program to implement string matching using Brute force
4 Write a program to implement Merge Sort
5 Write a program to implement Quick Sort
6 Write a program to obtain minimum cost spanning tree using Prim’s Algorithm
7 Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm
8 Write a program to obtain shortest path using Djikstra’s algorithm
9 Write a program to compute Binomial Coefficient
10 Write a program to obtain shortest path using Floyds algorithms
11 Write a program to compute Transitive closure using Warshall’s algorithm
12 Write a program to implement Breadth First search
13 Write a program to implement Depth First search
14 Write a program to implement Topological sorting
15 Write a program to implement Subset Sum problem using Backtracking
16 Write a program to implement N Queens problem using Backtracking
EXERCISE 1
1. Write a program to find GCD of two numbers using different algorithms
def gcde(m,n):
if m< n:
(m,n) = (n,m)
while n!=0:
r=m % n
m=n
n=r
return m
def gcdc(m,n):
t=min(m, n)
while t > 0:
if m % t == 0 and n % t == 0:
return t
t =t - 1
Explanation:
The program takes two numbers and prints the GCD of two numbers.
def : It is used to define the function in python , which can take the arguments.
input(): Function is used to take input from the user
int(input) :To take integer input in Python. The Python’s built-in input () function
always returns a str(string) class object. So for taking integer input we have to type cast
those inputs into integers by using Python built-in int () function.
Euclid Algorithm :
1.Take two numbers from the user.
2. Pass the two numbers as arguments to a recursive function.
If m < n ,interchange as we do m % n
3. When the second number becomes 0, return the first number.
4. Else recursively call the function with the arguments as the second number and
the remainder when the first number is divided by the second number.
5. Return the first number which is the GCD of the two numbers.
6. Print the GCD.
7. Exit.
def SieveOfEratosthenes(n):
if (prime[p] == True):
Explanation:
Prime = [True for i in range(n+1) : Print True for all till n value
It is one of the simple, ancient algorithm for finding all prime numbers up to any given limit.
The Steps in simple form
Mark the table with all true values initially and later follow the given steps
1. Generate numbers from 2 to n (2 is the smallest prime).
2. Traverse from smallest prime number which is num = 2.
3. Eliminate or mark all the multiples of num (as 0 or -1) which are lesser than or equal to n. It
will help remove non-prime numbers and will help to reduce our number of comparisons to
check for each number.
4. Update the value of num to the immediate next prime number. The next prime is the next
(non 0 or -1) number in the list which is greater than the current number (num).
5. Repeat step three until num<=√n.
Traverse the whole list and number print. All the numbers (>=0) will be our required prime
numbers lesser than n (given number).
if (j == M):
print("Pattern found at index ", i)
Explanation:
do
if (text letter == pattern letter)
compare next letter of pattern to next
letter of text
else
move pattern down text by one letter
while (entire pattern found or end of text)
Example :
.... N)
AAAAAAAAAAAAAAAAAAAAAAAAAAAH 5 comparisons made
AAAAH
Time Complexity
Explanation :
quicksort(alist, start, p)
quicksort(alist, p + 1, end)
pivot = alist[start]
i = start + 1
j = end - 1
while True:
i=i+1
j=j-1
if i <= j:
else:
return j
quicksort(alist, 0, len(alist))
print(alist)
Time Complexity : Best and Avg case : O(n log n),Worst Case :O(n 2)
EXERCISE 6
6. Write a program to obtain minimum cost spanning tree using Prim’s Algorithm
# Prim's Algorithm in Python
INF = 9999999
# number of vertices in graph
V=5
# create a 2d array of size 5x5
# for adjacency matrix to represent graph
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
# create a array to track selected vertex
# selected will become true otherwise false
selected = [0, 0, 0, 0, 0]
# set number of edge to 0
no_edge = 0
# the number of egde in minimum spanning tree will be
# always less than(V - 1), where V is number of vertices in
# graph
# choose 0th vertex and make it true
selected[0] = True
# print for edge and weight
print("Edge : Weight\n")
while (no_edge < V - 1):
# For every vertex in the set S, find the all adjacent vertices
#, calculate the distance from the vertex selected at step 1.
# if the vertex is already in the set S, discard it otherwise
# choose another vertex nearest to selected vertex at step 1.
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
# not in selected and there is an edge
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1
Explanation : Pseudocode
VT ← {v0} //the set of tree vertices can be initialized with any vertex
ET ← ∅
for i ← 1 to |V | − 1 do
find a minimum-weight edge e∗ = (v∗, u∗) among all the edges (v, u)
such that v is in VT and u is in V − VT
VT ← VT ∪ {u∗}
ET ← ET ∪ {e∗}
return ET
Steps:
1. Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex (there exists an edge
from a tree vertex, or unseen )that has minimum weight
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T
5. [END OF LOOP]
Time Complexity
EXERCISE 7
7. Write a program to obtain minimum cost spanning tree using Kruskal’s Algorithm
class Graph:
def init (self, vertices):
self.V = vertices
self.graph = []
# Search function
def kruskal_algo(self):
result = []
i, e = 0, 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
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("%d - %d: %d" % (u, v, weight))
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()
Explanation :
Steps:
First, sort all the edges from low weight to high.
Now, take the edge with the lowest weight and add it to the spanning tree. If the edge to be added
creates a cycle, then reject the edge.
Continue to add the edges until we reach all vertices, and a minimum spanning tree is created.
Pseudocode :
A lambda function can take any number of arguments, but can only have one expression.
lambda arguments : expression
lambda function includes three elements:
Lambda has used inside the sorted() function to sort the list. The graph is given as the first
argument value, the lambda has been set as the key value,
This will sort the graph edges based on the second item of each tuple and the print() function
has used to print the sorted list with space.
EXERCISE 8
8. Write a program to obtain shortest path using Djikstra’s algorithm
import sys
class Graph():
def __init (self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
Explanation :
● Create a set sptSet (shortest path tree set) that keeps track of vertices included in the
shortest-path tree, i.e., whose minimum distance from the source is calculated and
finalized. Initially, this set is empty.
● Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first.
● While sptSet doesn’t include all vertices
● Pick a vertex u which is not there in sptSet and has a minimum distance value.
● Include u to sptSet.
● Then update distance value of all adjacent vertices of u.
● To update the distance values, iterate through all adjacent vertices.
● For every adjacent vertex v, if the sum of the distance value of u
(from source) and weight of edge u-v, is less than the distance value
of v, then update the distance value of v.
●
Self Keyword
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class.
The sys module in Python provides valuable information about the Python interpreter. You can also
use it to obtain details about the constants, functions and methods of the Python interpreter.
Time Complexity :
n=5
k=2
print("Value of C[" + str(n) + "][" + str(k) + "] is " + str(binomialCoef(n, k)))
Explanation :
Algorithm BINO(n, k)
// n is total number of items
// k is the number of items to be selected from n
if k == 0 or k == n then
return 1
else
return _BINO(n – 1, k – 1) + BINO(n – 1, k)
end
import sys
INF = sys.maxsize
def floydWarshall(graph):
# number of vertices in the graph
n = len(graph)
# dist will be the output matrix that will have the shortest distances between every pair of vertex.
dist = [[] for i in range(n)]
# Initialize the dist matrix as same as the input graph matrix.
for i in range(n):
for j in range(n):
dist[i].append(graph[i][j])
# Taking all vertices one by one and setting them as intermediate vertices
for k in range(n):
# Pick all vertices as source one by one.
for i in range(n):
# Pick all vertices as the destination for the above choosen source vertex.
for j in range(n):
# Update the value of dist[i][j] if k provides a shortest path from i to j
dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j])
# Shortest distance for every pair of vertex.
print('Shortest Distance between every pair of vertex:-')
for i in range(n):
for j in range(n):
if dist[i][j]==INF:
print ("%7s" % ("INF"),end=' ')
else:
print ("%7s" % (dist[i][j]),end=' ')
print()
graph = [[0,5,INF,10],[INF,0,3,INF],[INF,INF,0,1],[INF,INF,INF,0]]
floydWarshall(graph)
Explanation :
class Graph:
def init (self, vertices): self.V
= vertices
def transitiveClosure(self,graph):
reach =[i[:] for i in graph]
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
reach[i][j] = reach[i][j] or (reach[i][k] and reach[k]
[j]) self.printSolution(reach)
g= Graph(4)
graph = [[1, 1, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]]
g.transitiveClosure(graph)
Algorithm :
Warshall(A[1...n, 1...n]) // A is the adjacency matrix
R(0) ← A
for k ← 1 to n do
for i ← 1 to n do
for j ← to n do
R(k)[i, j] ← R(k-1)[i, j] or (R(k-1)[i, k] and R(k-1)[k, j])
return R(n)
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
Explanation :
create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbors of u
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Explanation :
DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)
init() {
For each u ∈ G
u.visited = false
For each u ∈ G
DFS(G, u)
}
class Graph:
def __init (self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSortUtil(self,v,visited,stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
stack.insert(0,v)
def topologicalSort(self):
visited = [False]*self.V
stack =[]
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
print stack
g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
Explanation :
Time Complexity : O(V+E)
EXERCISE 15
15. Write a program to implement Subset Sum problem using Backtracking
if (sum == 0) :
return True
if (n == 0 and sum != 0) :
return False
Explanation :
1. Start with an empty set
2. Add the next element from the list to the set
3. If the subset is having sum M, then stop with that subset as solution.
4. If the subset is not feasible or if we have reached the end of the set, then backtrack through the
subset until we find the most suitable value.
5. If the subset is feasible (sum of seubset < M) then go to step 2.
6. If we have visited all the elements without finding a suitable subset and if no backtracking is
possible then stop without solution.
Pseducode
void subset_sum(int list[], int sum, int starting_index, int target_sum)
{
if( target_sum == sum )
{
subset_count++;
if(starting_index < list.length)
subset_sum(list, sum - list[starting_index-1], starting_index, target_sum);
}
else
{
for( int i = starting_index; i < list.length; i++ )
{
subset_sum(list, sum + list[i], i + 1, target_sum);
}
}
}
Time complexity : O(2^N)
EXERCISE 16
16. Write a program to implement N Queens problem using Backtracking