DAA Lab
DAA Lab
def fibonacci(n):
if n<0:
return 'Incorrect input'
elif n==0 or n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
n=int(input('Enter the number:'))
for i in range(n):
print(fibonacci(i),end=' ')
Output:
x = np.array([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[2, 2, 2, 2]])
y = np.array([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[2, 2, 2, 2]])
print('Matrix multiplication result:')
print(strassen_algorithm(x, y))
Output:
Sorted array is
5
6
7
11
12
13
Program: Coin Changing Problem
print("coin change")
def count(S, m, n):
table = [[0 for x in range(m)] for x in range(n + 1)]
for i in range(m):
table[0][i] = 1
for i in range(1, n + 1):
for j in range(m):
x = table[i - S[j]][j] if i - S[j] >= 0 else 0
y = table[i][j - 1] if j >= 1 else 0
table[i][j] = x + y
return table[n][m - 1]
arr = [1, 2, 3]
m = len(arr)
n=4
result = count(arr, m, n)
print("Number of ways to make change:", result)
Output:
coin change
Number of ways to make change: 4
Program: Warshall’s and Floyd’s algorithm
print("warshall’s floyd's algorithm")
nV = 4
INF = 999
def floyd(G):
dist = list(map(lambda p: list(map(lambda q: q, p)), G))
for r in range(nV):
for p in range(nV):
for q in range(nV):
dist[p][q] = min(dist[p][q], dist[p][r] + dist[r][q])
sol(dist)
def sol(dist):
for p in range(nV):
for q in range(nV):
if dist[p][q] == INF:
print("INF", end=" ")
else:
print(dist[p][q], end=" ")
print(" ")
G=[
[0, 5, INF, INF],
[50, 0, 15, 5],
[30, INF, 0, 15],
[15, INF, 5, 0]
]
floyd(G)
Output:
knapsack algorithm
220
Program: Dijkstra’s Algorithm
print("dijkstra's algorithm")
num_of_vertex = 7
def minimumDistance(distance, visited):
_min = float("inf")
min_index = -1
for i in range(num_of_vertex):
if not visited[i] and distance[i] <= _min:
_min = distance[i]
min_index = i
return min_index
def printParentNode(parent, i):
if parent[i] == -1:
return
printParentNode(parent, parent[i])
print("{} ".format(i + 1), end="")
def dijkstra(graph, src):
distance = list()
visited = list()
parent = list()
for i in range(num_of_vertex):
parent.append(-1)
distance.append(1e11)
visited.append(False)
distance[src] = 0
for i in range(num_of_vertex - 1):
U = minimumDistance(distance, visited)
visited[U] = True
for j in range(num_of_vertex):
curr_distance = distance[U] + graph[U][j]
if not visited[j] and graph[U][j] and curr_distance < distance[j]:
parent[j] = U
distance[j] = curr_distance
print("Vertex\t\tDistance\tPath")
for i in range(num_of_vertex):
path = getPath(parent, src, i)
print("{}->{}\t\t{}\t\t{}".format(src + 1, i + 1, distance[i], path))
def getPath(parent, src, j):
if parent[j] == -1:
return str(src + 1)
return getPath(parent, src, parent[j]) + " " + str(j + 1)
graph = [
[0, 1, 7, 6, 0, 0, 0],
[1, 0, 9, 0, 0, 3, 0],
[7, 9, 0, 0, 0, 0, 1],
[6, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 2, 0, 0, 0],
[0, 3, 0, 0, 0, 0, 3],
[0, 0, 1, 0, 0, 3, 0]
]
dijkstra(graph, 0)
Output:
Dijkstra's algorithm
Vertex Distance Path
1->1 0 1
1->2 1 12
1->3 7 13
1->4 6 14
1->5 8 145
1->6 4 126
1->7 7 1267
Program: Huffman Trees and codes
print("huffman trees and codes")
import heapq
class node:
def __init__(self, freq, symbol, left=None, right=None):
self.freq = freq
self.symbol = symbol
self.left = left
self.right = right
self.huff = ''
def __lt__(self, nxt):
return self.freq < nxt.freq
def printNodes(node, val=''):
newVal = val + str(node.huff)
if(node.left):
printNodes(node.left, newVal)
if(node.right):
printNodes(node.right, newVal)
if(not node.left and not node.right):
print(f"{node.symbol} -> {newVal}")
chars = ['a', 'b', 'c', 'd', 'e', 'f']
freq = [5, 9, 12, 13, 16, 45]
nodes = []
for x in range(len(chars)):
heapq.heappush(nodes, node(freq[x], chars[x]))
while len(nodes) > 1:
left = heapq.heappop(nodes)
right = heapq.heappop(nodes)
left.huff = 0
right.huff = 1
newNode = node(left.freq+right.freq, left.symbol+right.symbol, left,
right)
heapq.heappush(nodes, newNode)
printNodes(nodes[0])
Output:
Simplex Working....
Iteration: 1
B CB XB y1 y2 y3 y4
3 0 8 1 1 0 1
2 0 10 2 1 1 0
rel profit: 1, 1, 0, 0,
Iteration: 2
B CB XB y1 y2 y3 y4
3 0 3 0 1/2 -1/2 1
0 1 5 1 1/2 1/2 0
rel profit: 0, 1/2, -1/2, 0,
************************************
ALTERNATE Solution
optimal table:
B CB XB y1 y2 y3 y4
1 1 6 0 1 -1 2
0 1 2 1 0 1 -1
value of Z at optimality: 8
Final Basis: ['x2', 'x1']
Simplex Finished
Program: N-Queens problem
print("N-Queens problems")
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=' ')
print()
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
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):
return True
board[i][col] = 0
return False
def solveNQ():
board = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) is False:
print("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()
Output:
N-Queens problems
0010
1000
0001
0100
Program: Subset sum problem
print("subset sum problem")
def isSubsetSum(arr, n, target_sum):
if target_sum == 0:
return True
if n == 0:
return False
if arr[n - 1] > target_sum:
return isSubsetSum(arr, n - 1, target_sum)
return isSubsetSum(arr, n - 1, target_sum) or isSubsetSum(arr, n - 1,
target_sum - arr[n - 1])
set = [3, 34, 4, 12, 5, 2]
target_sum = 9
n = len(set)
if isSubsetSum(set, n, target_sum):
print("Found a subset with the given sum",target_sum)
else:
print("No subset with the given sum")
Output:
def branch_and_bound(cost_mat):
num_people = len(cost_mat)
assigned_jobs = [-1] * num_people
min_cost = [float('inf')]
best_asgmnt = None
cost_mat = np.array([
[5, 9, 1],
[10, 3, 2],
[8, 7, 4],
])
best_asgmnt, min_cost = branch_and_bound(cost_mat)
for person, job in enumerate(best_asgmnt):
print(f"Person {person + 1} - Job {job + 1}")
print(f"Minimum assignment cost: {min_cost}")
Output:
Person 1 - Job 1
Person 2 - Job 2
Person 3 - Job 3
Minimum assignment cost: 12
Program: Travelling Salesman Problem
from sys import maxsize
from itertools import permutations
V=4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation = permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path
if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print("the minimum cost is:",travellingSalesmanProblem(graph, s))
Output: