AD3351-Lab - Final - Student
AD3351-Lab - Final - Student
AIM:
To implement the recursive algorithm for finding factorial of a number using python.
ALGORITHM:
STEP1: start the
program.STEP2: get the
number.
STEP3: if number is equal to 1 return 1 other wise call recursively the factorial
function.
STEP4: return the factorial value
STEP5: print the factorial as the output.
PROGRAM:
def factorial(x):
"""This is a recursive function to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 5
print("The factorial of", num, "is", factorial(num))
OUTPUT:
120
RESULT:
DATE:
EX.NO: 1.B) NON RECURSIVE ALGORITHM
AIM:
To implement the Non-recursive algorithm using python.
ALGORITHM:
Step1. Read a number
Step2. Initialize fact as 1
Step3. If number is greater than 0, calculate factorial and decrement by 1.
Step4. Print the factorial value.
PROGRAM:
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)
OUTPUT:
Enter number:6
Factorial of the number is:
720
RESULT:
PROGRAM:
OUTPUT:
ABEICFJGDH
RESULT:
DATE:
EX.NO:2 DIVIDE AND CONQUER-STRASSEN’S MATRIX MULTIPLICATION
AIM:
To implement the strassen’s matrix multiplication using python.
ALGORITHM
Step1. Start the program.
Step2. Divide the matrices A and B into smaller submatrices of the size
n/2xn/2.Step3. Using the formula to carry out 2*2 matrix multiplication.
Step4. In this eight multiplications and four additions, subtractions are
performed. Step5. Combine the result of two matrices to find the final
product or final matrix.Step6. Stop the program.
PROGRAM:
import numpy as
npdef
split(matrix):
row,col=matrix.shape
row2,col2=row//2,col
/2
return
matrix[:row2,:col2],matrix[:row2,col2:],matrix[row2:,col2],matrix[row:,col2:]
def Strassen(x,y):
if lex(x)==1:
return x*y
a,b,c,d=split(
x)
e,f,g,h=split(y)
p1=strassen(a,f-1)
p2=strassen(a+b,h)
p3=strassen(c+d,e)
p4=strassen(d,g-e)
p5=strassen(a+d,e+
h)p6=strassen(b-
d,g+h)
p7=strassen(a-
c,e+f) c11=p5+p4-
p2+p6 c12=p1+p2
c21=p3+p4
c22=p1+p5-p3-p7
c=np.vstack((np.hstack((c11,c12)),hp.hstack((c21,c22))))
return c
OUTPUT:
Array A =>
1 1 1 1
2 2 2 2
3 3 3 3
2 2 2 2
Array B =>
1 1 1 1
2 2 2 2
3 3 3 3
2 2 2 2
Result Array =>
8 8 8 8
16 16 16 16
24 24 24 24
16 16 16 16
RESULT:
DATE:
EX.NO: 3.A) TOPOLOGICAL SORTING
AIM:
To implement the selection sort using python.
ALGORITHM:
Step1.Identify the node that has no in-degree (no incoming edges) and select that
node as thesource node of the graph.
Step2.Delete the source node with zero in-degree and also delete all its outgoing
edges from thegraph. Insert the deleted vertex in the result array.
Step3.Update the in-degree of the adjacent nodes after deleting the
outgoing edgesStep4.Repeat step 1 to step 3 until the graph is empty.
PROGRAM:
OUTPUT:
RESULT:
DATE:
EX.NO:4 TRANSFORM AND CONQUER -HEAP SORT
AIM:
To implement the Heapsort using python.
ALGORITHM:
Step1. Define a function heapify().
Step2. Pass three parameters array,a
and b. Step3. Find largest among root and
children.
Step4. If the root is not the largest,swap it with the
children.Step5. Continue to heapify.
Step6. Define function
Heap_Sort().Step7. Pass array as
parameters.
Step8. Build Max-heap and swap.
PROGRAM:
if largest != i:
(arr[i], arr[largest]) = (arr[largest], arr[i]) # swap
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
# Build a maxheap.
# Since last parent will be at ((n//2)-1) we can start at that location.
OUTPUT:
Sorted array
is5 6 7 11 12
13
RESULT:
DATE:
EX.NO:5 A) DYNAMIC PROGRAMMING-COIN CHANGE PROBLEMAIM:
ALGORITHM:
Step1. Start the program.
Step2. Two choices for a coin of a particular denominator either to include or to exclude.
Step3. At coins[n-1], we can take as , any instances of that can ie , count(coins ,n,
sum-coins[n- i])then we can move to coins[n-2].
Step4. After moving to coins [n-2], we can’t move back and can’t make choices for
coins [n-1]ie, count (coins , n-1 , sum).
Step5. Find the total number of ways , to we will add these – possible choices. ie)
count(coins ,n ,sum-coins[n-1])+ count(coins , n-1 ,sum ).
Step6. Stop the program.
PROGRAM:
def count(S, target):
# if the total is 0, return 1
if target == 0:
return 1
# return 0 if total becomes negative
if target < 0:
return 0
# initialize the total number of ways to 0
result = 0
# do for each coin
for c in S:
# recur to see if total can be reached by including current coin `c`
result += count(S, target - c)
if __name__ == '__main__':
OUTPUT:
The total number of ways to get the desired change is 7
RESULT:
DATE:
EX.NO.5 B) DYNAMIC PROGRAMMING-WARSHALL’S AND FLOYD’S ALGORITHM
AIM:
ALGORITHM:
OUTPUT:
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0
RESULT:
DATE:
EX.NO.5 (C) DYNAMIC PROGRAMMING-KNAPSACK PROBLEMAIM:
ALGORITHM:
PROGRAM:
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
return K[n][W]
OUTPUT:
220
RESULT:
DATE:
EX.NO 6.A) GREEDY TECHNIQUES- DIJKSTRA’S ALGORITHM
AIM:
To implement Dijkstra’s algorithm using python.
ALGORITHM:
Step1. Initialize the distance from the source node S to all other nodes as infinite
and to itselfas 0.
Step2. Insert the pair of node, distance for source i.e S, 0 in a DICTIONARY
Step3. While the DICTIONARY is not empty do
Step4. current_source_node = DICTIONARY . get_key (node)_with_smallest_value
(dist)Step5. Remove the key (current_source_node) from the DICTIONARY.
Step6. For every adjacent_node to the
current_source_node doStep7. If ( distance
[ adjacent_node ] >
Step8. length_of_path_to_adjacent_node_from_current_source +
distance[ current_source_node ] )
Step9. distance[adjacent_node ] =length_of_path_to_adjacent_node_from_current_source
+distance[ current_source_node ]
Step10. Update the DICTIONARY with the new pair < adjacent_node,
distance [adjacent_node ] >
PROGRAM:
class Node_Distance :
class Graph :
self.adjlist = defaultdict(list)
self.node_count = node_count
# Initialize the distance of all the nodes from the source node to infinity
distance = [999999999999] * self.node_count
# Distance of source node to itself is 0
distance[source] = 0
# Edge relaxation
if distance[adjnode] > distance[current_source_node] + length_to_adjnode :
distance[adjnode] = distance[current_source_node] + length_to_adjnode
dict_node_length[adjnode] = distance[adjnode]
for i in range(self.node_count) :
print("Source Node ("+str(source)+") -> Destination Node(" + str(i) + ") : " +
str(distance[i]))
def main() :
g = Graph(6)
g.Dijkstras_Shortest_Path(0)
print("\n")
g.Dijkstras_Shortest_Path(5)
if __name__ == "__main__" :
main()
OUTPUT:
RESULT:
DATE:
EX.NO:6. B) HUFFMAN TREES AND CODES
AIM:
To implement the Huffmann trees and codes using python.
ALGORITHM:
Step1. Calculate the frequency of each character in the string.
Step2. Sort the characters in increasing order of the frequency.
Step3. Make each unique character as a leaf node.
Step4. Create an empty node. Assign the minimum frequency to the left child of empty node
and assign the second minimum frequency to the right child of empty node . Set the
value of the empty node as the sum of the above two minimum frequencies.
Step5. Remove these two minimum frequencies from list and add the sum into the list of
frequencies.
Step6. Insert node into the tree.
Step7. Repeat steps 3 to 5 for all the characters.
Step8. For each non-leaf node, assign 0 to the left edge and 1 to the right edge.
PROGRAM:
# frequency of characters
freq = [ 5, 9, 12, 13, 16, 45]
# list containing unused nodes
nodes = []
heapq.heappush(nodes, newNode)
OUTPUT:
f -> 0
c -> 100
d -> 101
a -> 1100
b -> 1101
e -> 111
RESULT:
DATE:
EX.NO:7 ITERATIVE IMPROVEMENT-SIMPLEX METHOD
ALGORITHM:
Step1.Standard form.
Step2.Determine stack
variable.Step3.Setting up the
tableau.
Step4.Check optimality.
Step5.Identify pivot .
Step6.Create the new
tableau.Step7.Check
optimality.
Step8. Identify new pivot
variable.Step9.rom simplex
import simplex
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,20,10000)
y1 = 11.0 + x
y2 = 27.0 - x
y3 = (90-2*x)/5.0
plt.plot(x,y1,label = r'$-x+y\leq11$')
plt.plot(x,y2,label = r'$x+y\leq27$')
plt.plot(x,y3,label = r'$2x+5y\leq90$')
#plt.xlim((0, 20))
#plt.ylim((0, 40))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
y5 = np.minimum(y1, y2)
plt.fill_between(x, y3, y5, where=y3<y5, color='grey', alpha=0.5)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
OUTPUT:
RESULT:
DATE:
EX.NO.8 (A) BACKTRACKING -N QUEEN PROBLEM
AIM:
ALGORITHM:
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
0010
1000
0001
0100
RESULT;
DATE:
EX.NO.8(B) BACKTRACKING -SUBSET SUM PROBLEMAIM:
ALGORITHM:
Step3. If the numbers in the set sum up to given target_sum, It is a solution set
Step4. 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.
Step6.If we have traversed all the elements and if no backtracking is possible, then stop
without solution.
PROGRAM:
def sum_of_subset(s,k,rem):
x[k]=1
if s+my_list[k]==target_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]<=target_sum :
sum_of_subset(s+my_list[k],k+1,rem-my_list[k])
if s+rem-my_list[k]>=target_sum and s+my_list[k+1]<=target_sum :
x[k]=0
sum_of_subset(s,k+1,rem-my_list[k])
my_list=[]
n=int(input("Enter number of elements"))
total=0
for i in range (0,n):
ele=int(input())
my_list.append(ele)
total=total+ele
my_list.sort()
target_sum=int(input("Enter required Sum"))
x=[0]*(n+1)
sum_of_subset(0,0,total)
OUTPUT:
RESULT:
DATE:
EX.NO:9.A) BRANCH AND BOUND-ASSIGNMENT PROBLEM
AIM:
To implement the assignment problem using python.
ALGORITHM:
Step1. For each row of the matrix, find the smallest element and subtract it from every
elementin its row.
Step2. Repeat the step 1 for all columns.
Step3. Cover all zeros in the matrix using the minimum number of horizontal and vertical
lines.
Step4. Test for Optimality: If the minimum number of covering lines is N, an
optimal assignment is possible. Else if lines are lesser than N, an optimal
assignmentis not found and must proceed to step 5.
Step5. Determine the smallest entry not covered by any line. Subtract this entry
fromeach uncovered row, and then add it to each covered column. Return
to step 3
PROGRAM:
OUTPUT:
4
RESULT:
DATE:
EX.NO:9.B) BRANCH AND BOUND-TRAVELLING SALESMAN PROBLEM
ALGORITHM:
cities
Step3. Calculate the cost of every permutation and keep track of the minimum cost
import math
maxsize = float('inf')
def copyToFinal(curr_path):
final_path[:N + 1] = curr_path[:]
final_path[N] = curr_path[0]
min = maxsize
for k in range(N):
min = adj[i][k]
return min
for j in range(N):
if i == j:
continue
second = first
first = adj[i][j]
adj[i][j] != first):
second = adj[i][j]
return second
global final_res
# base case is when we have reached level N
if level == N:
if adj[curr_path[level - 1]][curr_path[0]] != 0:
[curr_path[0]]
copyToFinal(curr_path)
final_res = curr_res
return
for i in range(N):
if (adj[curr_path[level-1]][i] != 0 and
visited[i] == False):
temp = curr_bound
if level == 1:
firstMin(adj, i)) / 2)
else:
bound
curr_path[level] = i
visited[i] = True
curr_bound = temp
for j in range(level):
if curr_path[j] != -1:
visited[curr_path[j]] = True
def TSP(adj):
curr_bound = 0
curr_path = [-1] * (N + 1)
visited = [False] * N
for i in range(N):
curr_bound += (firstMin(adj, i) +
secondMin(adj, i))
curr_bound = math.ceil(curr_bound / 2)
# in curr_path[] is 0
visited[0] = True
curr_path[0] = 0
# Driver code
N=4
final_path = [None] * (N + 1)
visited = [False] * N
# of shortest tour.
final_res = maxsize
TSP(adj)
OUTPUT:
Minimum cost : 80
Path Taken : 0 1 3 2 0
RESULT: