DAA_RECORD_FINAL_COPY
DAA_RECORD_FINAL_COPY
DAA_RECORD_FINAL_COPY
NO. NO.
1
Ex.No:1(a) RECURSIVE ALGORITHM -
FIBONACCI SERIES
Date:
AIM:
To write the algorithm and python program to display the Fibonacci series usingrecursive
algorithm
ALGORITHM:
Step-3: Check if n is less than or equal to 1, if yes, then return the value of n to the main.
CODING:
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
n_terms <= 0:
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
2
Output
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
RESULT: Thus the Fibonacci series was displayed successfully using recursion algorithm and
output was verified.
3
Ex.No:1 b
BINARY SEARCH USING ITERATION METHOD
Date:
AIM:
To write an algorithm and python program to implement the binary search methodusing
non-recursive(Iteration) method.
ALGORITHM:
Step-5: Assume the value of mid and check if v[mid] < search element, then assign lo=mid=1.
Step-6: Otherwise assign hi = mid : and the loop runs until the condition fails.
Step-7: Return the value of mid to main program after the execution of while loop.
CODING:
if v[lo] == To_Find:
print("Found At Index", lo)
elif v[hi] == To_Find:
print("Found At Index", hi)
else:
print("Not Found")
4
To_Find)To_Find = 10
binarySearch(v, To_Find)
OUTPUT:
RESULT:
Thus the implementation of binary search using iterative method was executed
successfully and output was verified.
5
Ex.No: 2 FINDING MINIMUM AND MAXIMUM ELEMENT IN ARRAY USING
Date: DIVIDEAND CONQUER
AIM:
To write the algorithm and python program for finding the maximum and minimum
element in array using Divide and Conquer method.
ALGORITHM:
Step-2: Divide and conquer approach for Max. Min problem works in three stages.
Step-2.1: If a1 is the only element in the array, a1 is the maximum and minimum.
Step-2.2: If the array contains only two elements a1 and a2, then the single comparison between
two elements can decide the minimum and maximum of them.
Step-2.3: If there are more than two elements, the algorithm divides the array from the middle and
creates two subproblems.
Step-3: Both subproblems are treated as an independent problem and the same recursiveprocess is
applied to them.
Step-4: This division continues until subproblem size becomes one or two.
Step-5: After solving two subproblems, their minimum and maximum numbers are compared to
build the solution of the large problem.
Step-6: This process continues in a bottom-up fashion to build the solution of a parent problem.
CODING:
6
else:
return maximum;
def divideAndConquer_Min(arr, ind, len):
minimum = 0;
if (ind >= len - 2):
if (arr[ind] < arr[ind + 1]):
return arr[ind];
else:
return arr[ind + 1];
if __name == '__main__':
array initialization
arr = [6, 4, 8, 90, 12, 56, 7, 1, 63];
OUTPUT
RESULT:
Thus the implementation of divide and conquer method is executed successfully andoutput
was verified.
7
Ex.No:3
Date: DECREASE AND CONQUER - TOPOLOGICAL SORTING
AIM:
To write the algorithm and python program to implement the Topological sorting using
Decrease and Conquer method.
ALGORITHM:
Step-3: Initialize visited array of size N to keep the record of visited nodes.
Step-4.2: Call the recursive function for topological sort and perform the following steps.
Step-4.4: Run a loop on all the nodes which has a directed edge to the current node
CODING:
Graph:
def __init__(self,vertices):
def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSortUtil(self,v,visited,stack):
8
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)stack.insert(0,v)
[False]*self.Vstack =[]
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);
g.topologicalSort()
OUTPUT
2, 3, 1, 0]
RESULT:
Thus the implementation of topological sorting using decrease and conquermethod was
executed successfully and output was verified.
9
Ex.No: 4
Date: TRANSFORM AND CONQUER - HEAP SORT
AIM:
To write algorithm and python program to implement the Heap sorting using Transform
and Conquer algorithm.
ALGORITHM:
Step-2: Initialize largest as root and assign left=2*i+1 and right = 2*i+2.
Step-4: At this point, the maximum element is stored at the root of the heap.
Step-5: Replace it with the last item of the heap followed by reducing the size of the heap by 1.
Step-7: Repeat step 4 while the size of the heap is greater than 1.
CODING
largest = il
= 2 * i + 1r
=2*i+2
largest = l
largest = r
if largest != i:
heapify(arr, n, largest)
10
def heapSort(arr):
n = len(arr)
heapify(arr, n, i)
heapify(arr, i, 0)
heapSort(arr)n = len(arr)
in range(n):
print(arr[i])
OUTPUT
11
12
13
RESULT:
Thus the program had executed successfully and output was verified.
11
Ex.No: 5a DYNAMIC PROGRAMMING - COIN CHANGING PROBLEM
Date:
AIM:
To write the algorithm and python program to implement the coin changeproblem using
dynamic programming.
ALGORITHM
Step-2: The size of the dynamic progTable is equal to (number of coins +1)*(Sum +1).
Step-3: The first column value is one because there is only one way to change if the totalamount is 0.
(we do not include any coin).
Step-4: Row: The total number of coins. The fact that the first-row index is 0 indicatesthat no coin
is available. If the value index in the second row is 1, only the first coin is available.
Step-5: If the value index in the third row is 2, it means that the first two coins areavailable to add
to the total amount, and so on
Step-6: Column: Total amount (sum). Because the first-column index is 0, the sumvalue is 0. The
second column index is 1, so the sum of the coins should be 1.
Step-8: If the coin value is greater than the dynamicprogSum, the coin is ignored, i.e.
dynamicprogTable[i][j]=dynamicprogTable[i-1][j].
Step-9: If the coin value is less than the dynamicprogSum, you can consider it.
CODING
INF = 100000
if x < y:
return x
return y
12
for j in range(1, n+1):
minimum = INF
M[j] = minimum
return M[n]
if name == '__main__':
d = [0, 1, 2, 3]
print(coin_change(d, 5, 3))
OUTPUT
RESULT:
Thus the implementation of coin change problem was executed successfullyand output was
verified.
13
Ex.No:5b DYNAMIC PROGRAMMING -
Date: WARSHALL’S & FLOYD’S ALGORITHM
AIM:
To write the algorithm and python program to implement the warshall’s and floyd’s algorithm using
dynamic programming.
ALGORITHM:
Step-2: Initialize the shortest paths between any 2 vertices with Infinity.
Step 3: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest paths that use
1 intermediate vertex and so on.. until using all N vertices as intermediate nodes.
Step 4: Minimize the shortest paths between any 2 pairs in the previous operation.
Step 5: For any 2 vertices (i,j) , one should actually minimize the distances between this pairusing
the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).
CODING:
nV = 4
INF = 999
def floyd_warshall(G):
range(nV):
in range(nV):
print_solution(distance)
def print_solution(distance):for i
in range(nV):
for j in range(nV):
if(distance[i][j] == INF):
14
else:
[INF, 1, 0, INF],
floyd_warshall(G)
OUTPUT
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0
RESULT:
Thus the implementation of warshall’s and floyd’s algorithm was executed successfully
and output was verified.
15
Ex.No:5c DYNAMIC PROGRAMMING -
Date: KNAPSACK PROBLEM
AIM:
To write the algorithm and python program to implement the knapsack problem using
dynamic programming
CODING:
in range(n + 1):
if i == 0 or w == 0:
K[i][w] = 0
else:
K[i][w] = K[i-1][w]
return K[n][W]
W = 50
val, n))
OUTPUT
220
RESULT
16
Ex.No:6a GREEDY TECHNIQUES
Date: DIJIKSTRA’S ALGORITHM
AIM
To write the algorithm and python program to implement the dijikstra’salgorithm using greedy technique.
ALGORITHM
Step-2: Mark the source node with a current distance of 0 and the rest with infinity.
Step-3: Set the non-visited node with the smallest current distance as the current node,
lets say C.
Step-4: For each neighbour N of the current node C: add the current distance of C with
the weight of the edge connecting C-N.
Step-5: If it is smaller than the current distance of N, set it as the new current distance
of N.
CODING:
class Graph():
self.V = vertices
printSolution(self, dist):
node in range(self.V):
min = 1e7
17
for v in range(self.V):
min_index = v
return min_index
dist[src] = 0
cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
self.printSolution(dist)
g = Graph(9)
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[0, 0, 2, 0, 0, 0, 6, 7, 0]]
g.dijkstra(0)
18
OUTPUT
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
RESULT
Thus the implementation of dijikstra’s algorithm was executed successfullyand output
was verified.
19
Ex.No:6b HUFFMAN TREES AND CODES
Date:
AIM
To write the algorithm and python program to implement the Huffman trees andcodes using greedy
technique.
ALGORITHM
Step-4: Sort the characters in increasing order of the frequency. These are stored in a
priority queue Q.
Step-7: Create an empty node z. Assign the minimum frequency to the left child of z and
assign the second minimum frequency to the right child of z.
Step-8: Set the value of the z as the sum of the above two minimum
frequencies.Getting the sum of the least numbers
Step-9: Remove these two minimum frequencies from Q and add the sum into the list
of frequencies (* denote the internal nodes in the figure above).
Step-10: Insert node z into the tree.
Step-11: Repeat steps 3 to 5 for all the characters.
CODING:
string = 'BCAADDDCCACACAC'
class NodeTree(object):
self.left = left
self.right = right
20
def children(self):
type(node) is str:
= node.children()
d = dict()
freq = {}
for c in string:if
c in freq:
freq[c] += 1
else:
freq[c] = 1
freq
c1) = nodes[-1]
nodes = nodes[:-2]
nodes.append((node, c1 + c2))
huffmanCode = huffman_code_tree(nodes[0][0])
print('------------------------- ')
21
for (char, frequency) in freq:
OUTPUT
----------------------
'C' | 0
'A' | 11
'D' | 101
'B' | 100
RESULT:
Thus, the implementation of Huffman tress and codes was executed successfully and output was
verified.
22
Ex.No:7
ITERATIVE IMPROVEMENT - SIMPLEX ALGORITHM
Date:
AIM:
ALGORITHM :
Step-2: Start with the initial basis associated with identity matrix.
Step-4: For MAX problem check ,If all the relative profits are less than or equal to 0,then the
current basis is the optimal one. STOP.
Step-6: For MIN problem check If all the relative profits are greater than or equal to 0,then the
current basis is the optimal one. STOP.
Step-7:Else continue to 8.
Step-8: Find the column corresponding to max relative profit. Say column k has themax
Step-9: Perform a min ratio test to determine which variable will leave the basis.
Step-10: It's evident that the entered variable will not form an identity matrix, sowe will have to
perform row operations to make it identity again.
Step-11: Find the pivot element. The element at index (r, k) will be the pivot elementand row r will
be the pivot row.
Step-12: Divide the rth row by pivot to make it 1. And subtract c*(rth row) from otherrows to make
them 0, where c is the coefficient required to make that row 0.
Coding :
import numpy as np
b = np.array([8, 10])
c = np.array([1, 1, 0, 0])
23
cb = np.array(c[3])
B = np.array([[3], [2]])
cb = np.vstack((cb, c[2]))
xb = np.transpose([b])
MIN = 0
for el in row:
print()
print()
print("Simplex Working.")
reached = 0
itr = 1
unbounded = 0
alternate = 0
while reached == 0:
print(itr)
for el in row:
print()
i=0
rel_prof = []
24
while i<len(A[0]):
i]))i = i + 1
print()
i=0
b_var = table[:, 0]
while i<len(A[0]):
j=0
present = 0
while j<len(b_var):
if int(b_var[j]) == i:
present = 1
break;
j+= 1
if present == 0:
if rel_prof[i] == 0:
alternate = 1
i+= 1
print()
flag = 0
if profit>0:
flag = 1break
if flag == 0:
reached")reached = 1
break
k = rel_prof.index(max(rel_prof))min = 99999
25
i = 0;
r = -1
while i<len(table):
if (table[:, 2][i]>0 and table[:, 3 + k][i]>0):
k][i]if val<min:
min = valr = i
i+= 1
if r ==-1:
unbounded = 1
print("Case of Unbounded")break
pivot = table[r][3 + k]
i=0
while i<len(table):
if i != r:
print() i += 1
print("**************************************************
*************") if unbounded == 1:
print("UNBOUNDED LPP")
exit()
if alternate == 1:
26
print("ALTERNATE
Solution")print("optimal table:")
for el in row:
print()
print()
i=0
sum = 0
while i<len(table):
sum += c[int(table[i][0])]*table[i][2]
temp = "x"+str(int(table[i][0])+1)
basis.append(temp)
print(-Fraction(str(sum)).limit_denominator(100))
else:
print(Fraction(str(sum)).limit_denominator(100))
print("Simplex Finished...")
print()
OUTPUT:
Table at itr = 0
B CB XB y1 y2 y3 y4
3 0 8 1 1 0 1
27
2 0 10 2 1 1 0
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,
pivot element: 2
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
Iteration: 3
B CB XB y1 y2 y3 y4
1 1 6 0 1 -1 2
0 1 2 1 0 1 -1
**************************************************************
* ALTERNATE Solution
28
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
Simplex Finished...
RESULT:
29
Ex.No:8a BACKTRACKING -
Date: N-QUEEN PROBLEM
AIM:
To write the algorithm and python program to implement the n-queen problem using
backtracking algorithm.
ALGORITHM:
CODING:
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False def
N_queens(n):
if n==0:
30
return True
for i in range(0,N):
for j in range(0,N):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
OUTPUT:
[1, 0, 0, 0]
[0, 0, 1, 0]
RESULT:
Thus the implementation of n-queen problem was executed successfully and output was
verified.
31
Ex.No:8b SUBSET SUM PROBLEM
Date:
AIM:
To write the algorithm and python program to implement the subset sum problem.
ALGORITHM:
Step-4: If the numbers in the set sum up to given target_sum, It is a solution set.
Step-5: If the set doesnot sum upto the target_sum or if we have reached the end ofmy_list, then
backtrack the set until we find a solution set.
Step-7: If we have traversed all the elements and if no backtracking is possible, thenstop without
solution.
CODING:
return True
if (n == 0 and sum != 0) :
return False
sum = 9
n = len(set)
32
print("No subset with given sum")
OUTPUT:
RESULT:
Thus, the implementation of subset sum problem using backtracking algorithm was
executed successfully and output was verified.
33
BRANCH AND BOUND -
Ex.No:9
TRAVELLING SALESMAN PROBLEM
Date:
AIM:
To write the algorithm and python program to implement the travelling salesman problem
using branch and bound algorithm.
ALGORITHM
Consider city 1 as the starting and ending point. Since the route is cyclic, we canconsider any
point as a starting point.
Step-4: Calculate the cost of every permutation and keep track of the minimum costpermutation.
CODING:
=4
vertex = []
for i in range(V):
if i != s:
next_permutation=permutations(vertex)for i in next_permutation:
current_pathweight = 0k = s
for j in i:
current_pathweight += graph[k][j]
34
k=j
current_pathweight += graph[k][s]
return min_path
graph = [[0, 10, 15, 20], [10, 0, 35, 25],[15, 35, 0, 30], [20, 25, 30, 0]]
s = 0 print(travellingSalesmanProblem(graph, s))
OUTPUT
80
RESULT:
Thus, the implementation of salesman problem using branch and bound was executed
successfully and output was verified.
35