Design and Analysis of Algorithm Lab Manual - Answers
Design and Analysis of Algorithm Lab Manual - Answers
Prepared by:
Dr.M.Purushotham
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
def solve_nqueens(n):
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
return True
for i in range(n):
if is_safe(board, i, col):
board[i][col] = 1
if solve_util(board, col + 1):
return True
board[i][col] = 0
return False
board = [[0 for _ in range(n)] for _ in range(n)]
if solve_util(board, 0):
for row in board:
print(" ".join("Q" if val == 1 else "." for val in row))
else:
print("No solution exists.")
if __name__ == "__main__":
n = 20
solve_nqueens(n)
m = len(array)
for j in range(m):
for q in range(m - 1 - j):
if array[q][2] < array[q + 1][2]:
array[q], array[q + 1] = array[q + 1], array[q]
res = [False] * t
# To store result
job = ['-1'] * t
for q in range(len(array)):
if res[q] is False:
res[q] = True
job[q] = array[q][0]
break
# print
print(job)
# Driver
4) Write a pyton program to implement Dijkstra’s algorithm for the Single source
shortest path problem.
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
return min_index
self.printSolution(dist)
# Driver program
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)
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
# Search function
7) Write a python program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem
class KnapsackPackage(object):
""" Knapsack Package Data Class """
def __init__(self, weight, value):
self.weight = weight
self.value = value
self.cost = value / weight
class FractionalKnapsack(object):
def __init__(self):
pass
if __name__ == "__main__":
W = [15, 10, 2, 4]
V = [30, 25, 2, 6]
M = 37
n=4
proc = FractionalKnapsack()
proc.knapsackGreProc(W, V, M, n)