DAA MAnual for reference
DAA MAnual for reference
1
EXP NO: 1 RECURSIVE ALGORITHM
Date:
AIM: To write the algorithm and python program to display the Fibonacci series using
recursive 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
if 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-1.2 BINARY SEARCH USING RECURSION
Date:
AIM: To write an algorithm and python program to implement the Binary search algorithm
using recursion method.
ALGORITHM:
Step-2: Get the values for arr and search element x from the user.
Step-3: Inside the function definition binarySearch() Begin with the mid element of the whole
array as a search key.
Step-4: If the value of the search key is equal to the item then return an index of the search key.
Step-5: Or if the value of the search key is less than the item in the middle of the interval,
narrow the interval to the lower half.
Step-6: Otherwise, narrow it to the upper half.
Step-7: Repeatedly check from the second point until the value is found or the interval is empty
using the method of recursion until the base condition becomes True.
Step-8: Return the value of mid in base condition to the main program.
CODING:
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
arr = [2, 3, 4, 10, 40]
x = 10
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index % d" % result)
else:
print("Element is not present in array")
OUTPUT:
Element is present at index 3
Time Complexity: O(log n)
RESULT: Thus the binary search was displayed successfully using recursion algorithm and
output was verified.
4
EX-1.3 BINARY SEARCH USING ITERATION METHOD
Date:
AIM: To write an algorithm and python program to implement the binary search method
using non-recursive(Iteration) method.
ALGORITHM:
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")
OUTPUT:
Found At Index 4
Not Found
RESULT: Thus the implementation of binary search using iterative method was executed
successfully and output was verified.
5
EXP NO: 2 FINDING MINIMUM AND MAXIMUM ELEMENT IN ARRAY USING DIVIDE
AND CONQUER
Date:
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 recursive
process 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
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 and
output was verified.
7
EXP NO: 3 DECREASE AND CONQUER - TOPOLOGICAL SORTING
Date:
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:
class 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)
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);
g.topologicalSort()
OUTPUT
[5, 4, 2, 3, 1, 0]
RESULT: Thus the implementation of topological sorting using decrease and conquer
method was executed successfully and output was verified
9
EXP NO:4 TRANSFORM AND CONQUER - HEAP SORT
Date:
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 = i
l=2*i+1
r=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)
for i in range(n):
print(arr[i])
OUTPUT
Sorted array is
11
12
13
RESULT:
Thus the program had executed successfully and output was verified.
11
Exp No: 5 DYNAMIC CODINGMING
Date:
EX-5.1 COIN CHANGE PROBLEM
AIM: To write the algorithm and python program to implement the coin change
problem 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 total
amount 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 indicates
that 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 are
available to add to the total amount, and so on
Step-6: Column: Total amount (sum). Because the first-column index is 0, the sum
value 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
M = [0]*(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 successfully
and output was verified
13
EX-5.2 WARSHALL’S AND FLOYD’S ALGORITHM
Date:
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 pair
using 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):
for k in range(nV):
for i in range(nV):
for j 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:
print(" ")
[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-5.3 KNAPSACK PROBLEM
Date:
AIM: To write the algorithm and python program to implement the knapsack problem
using dynamic programming
ALGORITHM
CODING:
if i == 0 or w == 0:
K[i][w] = 0
else:
K[i][w] = K[i-1][w]
return K[n][W]
W = 50
n = len(val)
OUTPUT
220
16
EXP NO: 6 GREEDY TECHNIQUE
Date:
EX-6.1 DIJIKSTRA’S ALGORITHM
AIM To write the algorithm and python program to implement the dijikstra’s
algorithm 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
min = 1e7
17
for v in range(self.V):
min = dist[v]
min_index = v
return min_index
dist[src] = 0
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]
18
]
g.dijkstra(0)
OUTPUT
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
19
EX-6.2 HUFFMAN TREES AND CODES
Date:
AIM To write the algorithm and python program to implement the Huffman trees and
codes 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.
Step-12: Stop the program
CODING:
string = 'BCAADDDCCACACAC'
class NodeTree(object):
self.left = left
self.right = right
def children(self):
if type(node) is str:
(l, r) = node.children()
d = dict()
return d
freq = {}
for c in string:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
nodes = freq
nodes = nodes[:-2]
nodes.append((node, c1 + c2))
huffmanCode = huffman_code_tree(nodes[0][0])
21
print(' Char | Huffman code ')
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
EXP NO: 7 ITERATIVE IMPROVEMENT - SIMPLEX ALGORITHM
Date:
AIM: To write an algorithm and python program to implement the simplex algorithm
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 the
max
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, so
we 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 element
and 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 other
rows 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()
reached = 0
itr = 1
unbounded = 0
alternate = 0
while reached == 0:
print(itr)
for el in row:
print()
i=0
rel_prof = []
while i<len(A[0]):
i=i+1
24
print("rel profit: ", end =" ")
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 = 1
break
if flag == 0:
reached = 1
break
k = rel_prof.index(max(rel_prof))
min = 99999
i = 0;
r = -1
while i<len(table):
25
if (table[:, 2][i]>0 and table[:, 3 + k][i]>0):
if val<min:
min = val
r=i
i+= 1
if r ==-1:
unbounded = 1
print("Case of Unbounded")
break
print(np.array([r, 3 + k]))
pivot = table[r][3 + k]
print(Fraction(pivot).limit_denominator(100))
r, 2:len(table[0])] / pivot
i=0
while i<len(table):
if i != r:
i += 1
table[r][0] = k
table[r][1] = c[k]
print()
print()
itr+= 1
print()
print("***************************************************************")
if unbounded == 1:
print("UNBOUNDED LPP")
exit()
if alternate == 1:
26
print("ALTERNATE Solution")
print("optimal table:")
for el in row:
print()
print()
basis = []
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)
i+= 1
if MIN == 1:
print(-Fraction(str(sum)).limit_denominator(100))
else:
print(Fraction(str(sum)).limit_denominator(100))
print(basis)
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
EXP NO: 8 BACKTRACKING
Date:
EX-8.1 N-QUEEN PROBLEM
AIM: To write the algorithm and python program to implement the n-queen problem
using backtracking algorithm
ALGORITHM:
CODING:
N = int(input("Enter the number of queens : "))
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
30
return False
def N_queens(n):
if n==0:
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:
[0, 0, 0, 1]
[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-8.2 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 of
my_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, then
stop without solution.
CODING:
if (sum == 0) :
return True
if (n == 0 and sum != 0) :
return False
sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True) :
else :
32
print("No subset with given sum")
OUTPUT:
33
EXP NO: 9 BRANCH AND BOUND -- 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 can
consider any point as a starting point.
Step-4: Calculate the cost of every permutation and keep track of the minimum cost
permutation.
CODING:
from sys import maxsize
V=4
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]
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