ADA Lab Using Python Programming for BCA 5 th Sem NEP
DESIGN AND ANALYSIS OF ALGORITHMS
BCA – 5TH SEM
NEP
PRACTICAL MANUAL
USING PYTHON PROGRAMMING
RASHMI M A GFGCW- HNP 1
ADA Lab Using Python Programming for BCA 5 th Sem NEP
PART-A
1. Write a program to sort a list of N elements using
Selection Sort Technique.
2. Write a program to Solve Travelling Salesman Problem.
3. Write a Program to implement 0/1 Knapsack Problem using
dynamic Programming.
4. Write a program to implement DFS and BFS algorithm for a
graph.
5. Quick sort algorithm for sorting list of integers in
ascending order.
6. Quick Sort with Time Complexity for 5000 numbers.
7. Write a program to implement the backtracking algorithm
for the sum of subsets problem.
8. Implement function to print In-Degree, Out-Degree and to
display that matrix.
9. To Solve Optimal Binary Search Tree Problem.
PART-B
10. Write a program to find minimum and maximum value in an
array using divide and conquer technique.
11. Python program for implementation of Merge Sort.
12. Merge Sort with Time Complexity for 5000 Numbers.
13. 0-1 Fractional Knapsack problem using Greedy Solution.
14. Program for Job Sequencing problem using Greedy Technique.
15. Python program to solve N Queen Problem using backtracking
16. Create Adjacency Matrix for entered graph.
17. Prim’s Algorithm for Calculating MST using Greedy
Technique.
18. Kruskal’s Algorithm to calculate MST using Greedy
Technique.
RASHMI M A GFGCW- HNP 2
ADA Lab Using Python Programming for BCA 5 th Sem NEP
Part – A
RASHMI M A GFGCW- HNP 3
ADA Lab Using Python Programming for BCA 5 th Sem NEP
1.Write a program to sort a list of N elements using Selection Sort
Technique.
def Selection_Sort(array):
for i in range(0, len(array) - 1):
smallest = i
for j in range(i + 1, len(array)):
if array[j] < array[smallest]:
smallest = j
array[i], array[smallest] = array[smallest], array[i]
print("pass",i+1,"=",array)
array = input('Enter the list of numbers: ').split()
array = [int(x) for x in array]
Selection_Sort(array)
print('List after sorting is : ', end='')
print(array)
RASHMI M A GFGCW- HNP 4
ADA Lab Using Python Programming for BCA 5 th Sem NEP
2. Write a program to Solve Travelling Salesman Problem.
from sys import maxsize
from itertools import permutations
V = 4
def tsp(graph, s):
vertex = []
vertex.append(s);
for i in range(V):
if i != s:
vertex.append(i)
min_cost = maxsize
next_permutation = permutations(vertex)
for i in next_permutation:
current_cost = 0
k = s
for j in i:
current_cost += graph[k][j]
k = j
current_cost += graph[k][s]
if(i[0]==s):
print(i, '=', current_cost)
min_cost = min(min_cost, current_cost)
return min_cost
graph = [
[0, 20, 25, 10],
[20, 0, 35, 55],
[25, 35, 0, 40],
[10, 55, 40, 0]
]
src = 0
print("Possible Paths from source ",src)
total=tsp(graph, src)
print("Minimum cost among these path =", total);
RASHMI M A GFGCW- HNP 5
ADA Lab Using Python Programming for BCA 5 th Sem NEP
3.Write a Program to implement 0/1 Knapsack Problem using dynamic
Programming.
def myknapSack(W, wt, val, n):
K = [[0 for w in range(W + 1)] for i in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i - 1] <= w:
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i -
1]],K[i - 1][w])
else:
K[i][w] = K[i - 1][w]
res = K[n][W]
print("Maximum Profit can be earened =",res)
print("Weights of items which are included are")
w = W
for i in range(n, 0, -1):
if res <= 0:
break
if res == K[i - 1][w]:
continue
else:
print(wt[i - 1])
res = res - val[i - 1]
w = w - wt[i - 1]
#input for knapsack
val = [ 60, 100, 120, 80]
wt = [ 10, 20, 30, 15 ]
W = 70
n = len(val)
print("Capacity of Knapsack is =",W)
print("Weights of items are",wt)
print("Profit of items are",val);
myknapSack(W, wt, val, n)
RASHMI M A GFGCW- HNP 6
ADA Lab Using Python Programming for BCA 5 th Sem NEP
4. Write a program to implement DFS and BFS algorithm for a graph
def bfs(graph,start,path):
q=[start]
path.append(start)
while q:
node=q.pop(0)
for v in graph[node]:
if not v in path:
path.append(v)
q.append(v)
def dfs(graph,node,path):
path.append(node)
for v in graph[node]:
if v not in path:
dfs(graph,v,path)
graph={'A':['B','C'], 'B':['D','E'], 'C':['F'], 'D':[], 'E':[],
'F':[]}
dfs_path=[]
bfs_path=[]
dfs(graph,'A',dfs_path)
bfs(graph,'A',bfs_path)
print("DFS travel path:",dfs_path)
print("BFS travel path:",bfs_path)
RASHMI M A GFGCW- HNP 7
ADA Lab Using Python Programming for BCA 5 th Sem NEP
5. Write a test program to implement Divide and Conquer Strategy.
Eg: Quick sort algorithm for sorting list of integers in ascending
order.
import random
def partition(array, low, high):
pivot = array[high]
print("Pivot=",pivot,end='=')
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
print(array)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
alist = random.sample(range(1, 100), 10)
print('the unsorted elements are:',alist)
quickSort(alist, 0, len(alist)-1)
print('Sorted list: ', end='')
print(alist)
RASHMI M A GFGCW- HNP 8
ADA Lab Using Python Programming for BCA 5 th Sem NEP
6. Quick Sort with Time Complexity for 5000 numbers
import random
import time
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
alist = random.sample(range(1, 10000), 5000)
print('the unsorted elements are:',alist)
start_time=time.time()
quickSort(alist, 0, len(alist)-1)
print('Sorted list: ', end='')
end_time=time.time()
print(alist)
print("time taken for sorting is:",(end_time-start_time))
RASHMI M A GFGCW- HNP 9
ADA Lab Using Python Programming for BCA 5 th Sem NEP
7. Write a program to implement the backtracking algorithm for the
sum of subsets problem
def sum_of_subset(s,k,rem):
x[k]=1
if s+my_list[k]==t_sum:
list1=[]
for i in range (0,k+1):
if x[i]==1:
list1.append(my_list[i])
print( list1 )
elif s+my_list[k]+my_list[k+1]<=t_sum :
sum_of_subset(s+my_list[k],k+1,rem-my_list[k])
if s+rem-my_list[k]>=t_sum and s+my_list[k+1]<=t_sum :
x[k]=0
sum_of_subset(s,k+1,rem-my_list[k])
my_list=[]
n=int(input("Enter number of elements: "))
print("Enter the number list")
total=0
for i in range (0,n):
ele=int(input())
my_list.append(ele)
total=total+ele
my_list.sort()
t_sum=int(input("Enter required Sum: "))
x=[0]*(n+1)
sum_of_subset(0,0,total)
RASHMI M A GFGCW- HNP 10
ADA Lab Using Python Programming for BCA 5 th Sem NEP
8. Implement function to print In-Degree, Out-Degree and to display
that matrix.
def findInOutDegree(adjList, n):
_in = [0] * n
out = [0] * n
for i in range(0, len(adjList)):
List = adjList[i]
out[i] = len(List)
for j in range(0, len(List)):
_in[List[j]] += 1
print("Vertex\tIn\tOut")
for k in range(0, n):
print(str(k) + "\t" + str(_in[k]) +
"\t" + str(out[k]))
# Adjacency list representation of the graph
adjList = []
V=int(input("Enter the number of vertices: "))
for i in range(V):
print("Enter the number nodes having incoming edge from
node:",i)
E=int(input())
node_list=[]
for j in range(0,E):
node=int(input("Enter Node: "))
node_list.append(node)
adjList.append(node_list)
n = len(adjList)
findInOutDegree(adjList, n)
RASHMI M A GFGCW- HNP 11
ADA Lab Using Python Programming for BCA 5 th Sem NEP
9. To Solve Optimal Binary Search Tree Problem.
def optCost(freq, i, j):
if j < i:
return 0
if j == i:
return freq[i]
fsum = Sum(freq, i, j)
Min = 999999999999
for r in range(i, j + 1):
cost = (optCost(freq, i, r - 1) +
optCost(freq, r + 1, j))
if cost < Min:
Min = cost
return Min + fsum
def optimalSearchTree(keys, freq, n):
return optCost(freq, 0, n - 1)
def Sum(freq, i, j):
s = 0
for k in range(i, j + 1):
s += freq[k]
return s
keys = input('Enter the keys: ').split()
keys = [int(x) for x in keys]
freq = input('Enter the frequency for respective key: ').split()
freq = [int(x) for x in freq]
n = len(keys)
opt_cost=optimalSearchTree(keys, freq, n)
print("Cost of Optimal BST is",opt_cost)
RASHMI M A GFGCW- HNP 12
ADA Lab Using Python Programming for BCA 5 th Sem NEP
Part – B
RASHMI M A GFGCW- HNP 13
ADA Lab Using Python Programming for BCA 5 th Sem NEP
10. Write a program to find minimum and maximum value in an array
using divide and conquer technique.
def max_min_divide_conquer(arr, low, high):
class Pair:
def __init__(self):
self.max = 0
self.min = 0
result = Pair()
if low == high:
result.max = arr[low]
result.min = arr[low]
return result
if high == low + 1:
if arr[low] < arr[high]:
result.min = arr[low]
result.max = arr[high]
else:
result.min = arr[high]
result.max = arr[low]
return result
mid = (low + high) // 2
left = max_min_divide_conquer(arr, low, mid)
right = max_min_divide_conquer(arr, mid + 1, high)
result.max = max(left.max, right.max)
result.min = min(left.min, right.min)
return result
arr = input('Enter the list of numbers: ').split()
arr = [int(x) for x in arr]
result = max_min_divide_conquer(arr, 0, len(arr) - 1)
print(arr)
print("Maximum element is:", result.max)
print("Minimum element is:", result.min)
RASHMI M A GFGCW- HNP 14
ADA Lab Using Python Programming for BCA 5 th Sem NEP
11. Python program for implementation of Merge Sort.
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr, l, r):
if l < r:
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
arr = input('Enter the list of numbers: ').split()
arr = [int(x) for x in arr]
n = len(arr)
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
print(arr)
RASHMI M A GFGCW- HNP 15
ADA Lab Using Python Programming for BCA 5 th Sem NEP
12. Merge Sort with Time Complexity for 5000 Numbers.
import time
import random
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0, n1):
L[i] = arr[l + i]
for j in range(0, n2):
R[j] = arr[m + 1 + j]
i = 0; j = 0; k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr, l, r):
if l < r:
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
arr = random.sample(range(1, 10000), 5000)
n = len(arr)
start_time=time.time()
print("Given array is")
print(arr)
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
print(arr)
end_time=time.time()
print("time taken for sorting is:",(end_time-start_time))
RASHMI M A GFGCW- HNP 16
ADA Lab Using Python Programming for BCA 5 th Sem NEP
13. 0-1 Knapsack problem using Greedy Solution
def greedy_fractional_knapsack(values, weights, W):
n = len(values)
ratios = [(values[i] / weights[i], values[i], weights[i]) for i
in range(n)]
selected=[]
ratios.sort(reverse=True)
total_value = 0 # Initialize total value
current_weight = 0 # Initialize current weight
for ratio, value, weight in ratios:
if current_weight + weight <= W:
total_value += value
current_weight += weight
selected.append(1)
else:
fraction = (W - current_weight) / weight
total_value += value * fraction
selected.append(round(fraction,3))
break
#Printing Output
print("List of items")
print("Ratio, Profit, Weight, Selected")
p_ratios = [(ratios[i], selected[i]) for i in range(n)]
for x in p_ratios:
print(x)
return total_value
#input for Fractional KnapSack
print("Fractional Knapsack using Greedy Algorithm")
values1 = [60, 100, 200]
weights1 = [10, 20, 25]
Capacity = 50
profit=greedy_fractional_knapsack(values1, weights1, Capacity)
print("Maximum value in knapsack (Greedy Approach) =",profit)
RASHMI M A GFGCW- HNP 17
ADA Lab Using Python Programming for BCA 5 th Sem NEP
14. Program for Job Sequencing problem using Greedy Technique.
def printJobScheduling(arr, t):
n = len(arr)
for i in range(n):
for j in range(n - 1 - i):
if arr[j][2] < arr[j + 1][2]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
result = [False] * t
job = ['-1'] * t
profit =0
for i in range(len(arr)):
for j in range(min(t - 1, arr[i][1] - 1), -1, -1):
if result[j] is False:
result[j] = True
job[j] = arr[i][0]
profit = profit + arr[i][2]
break
print(job)
print("Maximum Profit=",profit)
arr = [['a', 2, 100],
['b', 1, 19],
['c', 2, 27],
['d', 1, 25],
['e', 3, 15],
['f', 4, 25]]
print("Job List")
print("JobName, Deadline, Profits are")
for i in arr:
print(i)
J=int(input("Enter the number of jobs to be selected before maximum
Deadline:"))
print("Following is maximum profit sequence of jobs")
printJobScheduling(arr, J)
RASHMI M A GFGCW- HNP 18
ADA Lab Using Python Programming for BCA 5 th Sem NEP
15. Python program to solve N Queen Problem using backtracking
global N
N = int(input("Enter number of Queens: "))
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
#to check whether selected place the queen is safe or not
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
#to place the queens on board usng 1 and 0
def solveNQUtil(board, col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False
#To check solution exists or not
def solveNQ():
board = [[0 for _ in range(N)] for _ in range(N)]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()
RASHMI M A GFGCW- HNP 19
ADA Lab Using Python Programming for BCA 5 th Sem NEP
16. Create Adjacency Matrix for Undirected graph.
class Graph(object):
# Initialize the matrix
def __init__(self, size):
self.adjMatrix = []
for i in range(size):
self.adjMatrix.append([0 for i in range(size)])
self.size = size
# Add edges
def add_edge(self, v1, v2):
if v1 == v2:
print("Same vertex %d and %d" % (v1, v2))
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def __len__(self):
return self.size
# Print the matrix
def print_matrix(self):
for row in self.adjMatrix:
for val in row:
print('{:4}'.format(val),end=" "),
print()
print("Creating Adjacency Matrix for Undirected Graph")
V=int(input("Enter the number of vertices: "))
g = Graph(V)
E=int(input("Enter the number of edges: "))
for i in range(E):
print("enter the src for edge-",i+1,end=" ")
src=int(input())
print("enter the destination for edge-",i+1,end=" ")
dest=int(input())
g.add_edge(src, dest)
g.print_matrix()
RASHMI M A GFGCW- HNP 20
ADA Lab Using Python Programming for BCA 5 th Sem NEP
17. Prim’s Algorithm for Calculating MST using Greedy Technique.
import heapq
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for _ in range(V)]
def add_edge(self, u, v, w):
self.adj[u].append((v, w))
self.adj[v].append((u, w))
def prim_mst(self):
pq = []
src = 0
key = [float('inf')] * self.V
parent = [-1] * self.V
in_mst = [False] * self.V
heapq.heappush(pq, (0, src))
key[src] = 0
while pq:
u = heapq.heappop(pq)[1]
if in_mst[u]:
continue
in_mst[u] = True
for v, weight in self.adj[u]:
if not in_mst[v] and key[v] > weight:
key[v] = weight
heapq.heappush(pq, (key[v], v))
parent[v] = u
for i in range(1, self.V):
print(f"{parent[i]} - {i}")
print("Prims Algorithm to calculate Minimum Spanning Tree")
V=int(input("Enter the number of vertices: "))
g = Graph(V)
E=int(input("Enter the number of edges: "))
for i in range(E):
print("enter the src for edge-",i+1,end=" ")
src=int(input())
print("enter the destination for edge-",i+1,end=" ")
dest=int(input())
print("enter the weight of the edge-",i+1,end=" ")
wt=int(input())
g.add_edge(src, dest,wt)
print("Selected Edges are")
g.prim_mst()
RASHMI M A GFGCW- HNP 21
ADA Lab Using Python Programming for BCA 5 th Sem NEP
18.Kruskal’s Algorithm to calculate MST using Greedy Technique.
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] != i:
parent[i] = self.find(parent, parent[i])
return parent[i]
def union(self, parent, rank, x, y):
if rank[x] < rank[y]:
parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x
else:
parent[y] = x
rank[x] += 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
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Weight in MST is :", minimumCost)
########################################################
RASHMI M A GFGCW- HNP 22
ADA Lab Using Python Programming for BCA 5 th Sem NEP
print("Kruskal's Algorithm to calculate MST")
V=int(input("Enter the number of vertices: "))
g = Graph(V)
E=int(input("Enter the number of edges: "))
for i in range(E):
print("enter the src for edge-",i+1,end=" ")
src=int(input())
print("enter the destination for edge-",i+1,end=" ")
dest=int(input())
print("enter the weight of the edge-",i+1,end=" ")
wt=int(input())
g.addEdge(src, dest, wt)
print("Selected Edges are")
g.KruskalMST()
RASHMI M A GFGCW- HNP 23