Daa Final
Daa Final
A. FACTORIAL OF N NUMBERS
AIM:
To find factorial of n numbers.
ALGORITHM:
1. Start the program.
2. Get the input from the user.
3. Define the function
4. If n=0 Return 1
5. Else Return n*fac (n-1)
6. Display the result.
7 Stop the program.
PROGRAM:
def recur_factorial(n):
if n == 1:
return n else:
return n*recur_factorial(n-1) num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers") elif num == 0:
print("The factorial of 0 is 1") else:
print("The factorial of",num,"is",recur_factorial(num))
OUTPUT:
Enter a number: 6
RESULT:
To find factorial of n number is executed successfully and verified.
B) FIBONACCI SERIES
AIM:
ALGORITHM:
PROGRAM:
OUTPUT:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
RESULT:
The Finding the Fibonacci series program executed successfully.
C) Binary representation of decimal number
AIM:
To represent the decimal number from binary.
ALGORITHM:
PROGRAM:
def bin(n):
if ( n > 0): bin((int)(n/2)) print(n%2,end = “ ”)
n = int(input(“Enter the decimal number : ”)) bin(n)
OUTPUT:
1000
RESULT:
The representation of decimal number has been executed successfully.
D) GCD OF TWO NUMBERS
AIM:
Python program to find the gcd of two numbers.
ALGORITHM:
1. First, we define a function named compute GCD(). This function accepts two integers x and y
as function parameters.
2. Next, we write a while loop that runs as long as y is not equal to 0.
Inside the while loop, we compute the remainder of x when divided by y.
3. At the end of the while loop, we update x and y with their new values.
4. Finally, we return the absolute value of x.
5. Now, we call the computeGCD() function with the integers 60 and 48
PROGRAM:
def computeGCD(x, y): while(y):
x, y = y, x % y
return abs(x)
a = 60
b = 48
print ("The gcd of 60 and 48 is : ",end="")
print (computeGCD(60, 48))
OUTPUT:
The gcd of 60 and 48 is: 12
RESULT:
Python program to find the gcd of two numbers is executed successfully.
E) REVERSAL OF A STRING
AIM:
Python program to reverse a given string.
ALGORITHM:
1. Start the program
2. Get the input from the user
3. Slice the string by giving the increment value as -1
4. Display the result
5. Stop the program
PROGRAM:
a = input(“Enter a string : ”)
print(“the given string is ”,a)
print(“reversal of the string is ”,a[::-1])
OUTPUT:
RESULT:
Python program to reverse a string is executed successfully.
F) BUBBLE SORT
AIM:
Python program for Bubble sort.
ALGORITHM:
1. We have an outer loop that runs for all elements in the array.
2. The outer loop is responsible for “passes”.
3. The inner loop is responsible for comparing and swapping adjacent elements.
4. The inner loop runs for all elements from the current pass.
5. The inner loop runs from 0 to n-i-1.
6. The inner loop runs for n-i-1 elements, but the outer loop runs n times.
7. The outer loop is responsible for reducing the total number of elements to sort.
PROGRAM:
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1): if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] if name == " main ":
arr = [5, 1, 4, 2, 8]
bubbleSort(arr) print("Sorted array is:") for i in range(len(arr)):
print("%d" % arr[i], end=" ")
OUTPUT:
Sorted array: 1 2 4 5 8
RESULT:
Python program for bubble sort is executed successfully.
G) BFS
AIM:
Python program for BFS program.
ALGORITHM:
1. First, we append the starting node to the visited list and the queue.
2. Then, we pop the first element of the queue and print it.
3. Then, we iterate through its adjacent nodes and add them to the queue.
4. If any of the adjacent nodes isn‟t visited, we add it to the visited list and the queue.
5. We keep doing this until the queue is empty.
PROGRAM:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] queue = []
def bfs(visited, graph, node): visited.append(node) queue.append(node)
while queue:
m = queue.pop(0) print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited: visited.append(neighbour) queue.append(neighbour)
print("Following is the Breadth-First Search") bfs(visited, graph, '5')
OUTPUT:
The BFS is 5 3 7 2 4 8
RESULT:
Python program for BFS is executed successfully.
EXP NO: 2 DATE:
Divide and Conquer - Strassen’s Matrix Multiplication
AIM:
To write a python program for Divide and Conquer - Strassen‟s Matrix Multiplication Problem
ALGORITHM:
1. Start
2. Divide the matrices A and B ints smaller submatrices of the size n/2 x n/2
3. Using the formula of scalar additions and subtraction compute smaller matrices of size n/2
4. Recursively compute the seven matrix products pi = AiBi, for i = 1,2, ,7
5. Now compute the r,s,t,u submatrices by just adding the scalars obtaining from above points
6. Stop
PROGRAM:
x=[[0,2],[0,1]]
print("matrix x is: ",x) for i in range(len(x)):
print("\t",x[i])
y=[[0,0],[3,4]]
print("matrix y is: ",y) for i in range(len(y)):
print("\t",y[i]) def st(a,b):
s=[b[0][1]-b[1][1],a[0][0]+a[0][1],
a[1][0]+a[1][1],b[1][0]-b[0][0],
a[0][0]+a[1][1],b[0][0]+b[1][1],
a[0][1]-a[1][1],b[1][0]+b[1][1],
a[0][0]-a[1][0],b[0][0]+b[0][1]]
p=[a[0][0]*s[0],s[1]*b[1][1],
s[2]*b[0][0],a[1][1]*s[3],
s[4]*s[5],s[6]*s[7],s[8]*s[9]]
c=[[p[4]+p[3]-p[1]+p[5],p[0]+p[1]],
[p[2]+p[3],p[4]+p[0]-p[2]-p[6]]]
print("strassens matrix multiplication is ") print(c)
st(x,y)
OUTPUT:
matrix x is: [[0, 2], [0, 1]]
[0, 2]
[0, 1]
matrix y is: [[0, 0], [3, 4]]
[0, 0]
[3, 4]
strassens matrix multiplication is [[6, 8], [3, 4]]
RESULT:
Python code for Divide and Conquer - Strassen‟s Matrix Multiplication Program executed
successfully.
EXP NO: 3 DATE:
Decrease and Conquer - Topological Sorting
AIM:
To write a python program for Decrease and Conquer in Topological Sorting.
ALGORITHM:
1. First, we make a defaultdict of type list.
2. Then, we add edges to the graph.
3. After that, we call the topologicalSortUtil() function on vertex 0.
4. Inside topologicalSortUtil(), we mark the current node as visited.
5. Then, we loop through all the adjacent nodes of the current node.
6. If the adjacent node is not visited, we recursively call the topologicalSortUtil() function on the
adjacent node.
7. Finally, we push the current node to the stack and pop the node from the stack and print it.
PROGRAM:
from collections import defaultdict class Graph:
def init (self,vertices):
self.graph = defaultdict(list) self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSortUtil(self,v,visited,stack): 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);
print("Following is a Topological Sort of the given graph") g.topologicalSort()
OUTPUT:
Following is a Topological Sort of the given graph: [5, 4, 2, 3, 1, 0]
RESULT:
Decrease and Conquer in Topological Sorting python program executed successfully.
EXP NO: 4 Date:
AIM:
To implement transform and conquer algorithm for Heapsort using python.
ALGORITHM:
1. Start the program.
2. Build a complete binary tree from the array.
3. After that construct a tree from that unsorted array and try to convert into max Heap.
4. Remove the maximum element in each step.
5. Repeat above steps.
6. Display the Result.
7. Stop the program.
PROGRAM:
def heapify(arr, N, i): largest = i
l = 2 * i + 1r
=2*i+2
if l < N and arr[largest] < arr[l]: largest = l
if r < N and arr[largest] < arr[r]: largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, N, largest)
def heapSort(arr):N
= len(arr)
for i in range(N//2 - 1, -1, -1): heapify(arr, N, i)
for i in range(N-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0)
if name == ' main ':arr
= [12, 11, 13, 5, 6, 7]
heapSort(arr) N = len(arr)
print("Sorted array is")for i in range(N):
print("%d" % arr[i], end=" ")
OUTPUT:
Sorted array is 5 6 7 11 12 13
RESULT:
Transform and conquer algorithm for Heap sort program Executed successfully.
EXP NO: 5 DATE:
Dynamic programming
A) Coin change Problem
AIM:
To write a python program for Dynamic programming in Coin change Problem.
ALGORITHM:
1. We have 2 choices for a coin of a particular denomination, either i) to include, or ii) to exclude
2. If we are at coins[n-1], we can take as many instances of that coin ( unbounded inclusion )
i.e count(coins, n, sum – coins[n-1] ); then we move to coins[n-2]
3. After moving to coins[n-2], we can‟t move back and can‟t make choices for coins[n-1]
i.e count(coins, n-1, sum)
4. Finally, as we have to find the total number of ways, so we will add these 2 possible choices,
i.e count(coins, n, sum – coins[n-1] ) + count(coins, n-1, sum )
PROGRAM:
def count(coins, n, sum):
if (sum == 0):
return 1 if (sum < 0):
return 0 if (n <= 0):
return 0
return count(coins, n - 1, sum) + count(coins, n, sum-coins[n-1]) coins = [1, 2, 3]
n = len(coins) print(count(coins, n, 4))
OUTPUT:
4
RESULT:
The dynamic program in coin changing problem executed successfully.
B ) Warshall’s and Floyd‘s algorithms
AIM:
To implement the dynamic program in Warshall‟s and Floyd„s algorithms
ALGORITHM:
1. Initialize the solution matrix same as the input graph matrix as a first step.
2. Then update the solution matrix by considering all vertices as an intermediate vertex.
3. The idea is to one by one pick all vertices and updates all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
4. When we pick vertex number k as an intermediate vertex, we already have considered vertices
{0, 1, 2, .. k-1} as intermediate vertices.
5. For every pair (i, j) of the source and destination vertices respectively, there are two possible
cases
6. k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it
is.
7. k is an intermediate vertex in shortest path from i to j.
We update the value of dist[i][j] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]
PROGRAM :
nV = 4
INF = 999
def floyd_warshall(G):
distance = list(map(lambda i: list(map(lambda j: j, i)), G)) for k in range(nV):
for i in range(nV):
for j in range(nV):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) print_solution(distance)
def print_solution(distance): for i in range(nV):
for j in range(nV): if(distance[i][j] == INF):
print("INF", end=" ")
else:
print(" ") G = [[0, 3, INF, 5],
[2, 0, INF, 4],
[INF, 1, 0, INF],
print(distance[i][j], end=" ")
[INF, INF, 2, 0]]
Floyd_warshall(G)
OUTPUT:
0375
2064
3105
5320
RESULT:
Implement the dynamic program in Warshall‟s and Floyd„s algorithms execute
successfully.
C ) Knapsack Problem
AIM:
To implement the dynamic programming in Knapsack Problem.
ALGORITHM:
1. First, we initialize a 2D array K[][] to store the maximum value.
2. Then, we loop through all the items and fill the K[][] array.
3. In each iteration, we check if the item can fit in the sack or not.
4. If it can fit, then we calculate the maximum of two cases:
a) Including the item.
b) Excluding the item.
5. We select the maximum of two cases and store it in K[][].
6. Finally, we return the last element from the K[][] array.
PROGRAM :
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else:
K[i][w] = K[i-1][w]
return K[n][W]
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val) print(knapSack(W, wt, val, n))
OUTPUT:
350
RESULT:
To implement the dynamic programming in Knapsack Problem executed successfully.
EXP NO : 6 DATE :
GREEDY TECHNIQUE
A) DIJKSTRA'S ALGORITHM
AIM:
To implement Dijkstra's algorithm using greedy technique
ALGORITHM:
1. First, we initialize all the distances to infinity and the source node to 0.
2. We then iterate through all the nodes in the graph.
3. We pick the minimum distance vertex from the set of vertices not yet processed. This is the
current source vertex.
4. We then find out all the adjacent vertices to the current source vertex.
If the current distance to the adjacent vertex is greater than the distance to the current source
vertex plus the weight of the edge between the two vertices, we update the distance of the
adjacent vertex.
5. We then mark the current source vertex as visited.
6. We then repeat steps 3 and 4 until all the vertices are visited.
PROGRAM :
class Graph():
def init (self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]for row in range(vertices)] def printSolution(self,
dist):
print("Vertex \t Distance from Source") for node in range(self.V):
print(node, "\t\t", dist[node]) def minDistance(self, dist, sptSet):
min = 1e7
for v in range(self.V):
if dist[v] < min and sptSet[v] == False: min = dist[v]
min_index = v
return min_index def dijkstra(self, src):
dist = [1e7] * self.V dist[src] = 0
sptSet = [False] * self.V for cout in range(self.V):
u = self.minDistance(dist, sptSet) sptSet[u] = True
for v in range(self.V):
if (self.graph[u][v] > 0 and sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
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)
OUTPUT:
RESULT:
Thus the Dijkstra's algorithm using greedy technique has been implemented successfully.
B) HUFFMAN TREES AND CODES
AIM:
To implement huffman tree coding using greedy technique.
ALGORITHM:
1. Create a list of characters and their frequencies.
2. Create a list of nodes.
3. Create a heap from the list of nodes.
4. Pop two nodes with the lowest frequency values and create a new node with the sum of these
two nodes‟ frequencies.
5. Assign 0 to the left node and 1 to the right node.
6. Push the new node back into the heap.
7. Repeat steps 3-6 until only one node remains.
PROGRAM:
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:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
RESULT:
Thus the huffman tree coding using greedy technique has been implemented successfully.
EXP NO: 7 DATE:
BACKTRACKING
A) N-QUEEN PROBLEMS
AIM:
To implement N-Queen problem using backtracking in python.
ALGORITHM :
1. First, we check if the column number is less than the number of columns in the board.
2. If it is, we check if the board is safe for the queen to be placed in the current row and
column.
3. If it is, we place the queen in that position and recursively call the same function for the next
column.
4. If placing the queen in the current position doesn‟t lead to a solution, then we backtrack and
place the queen in the next column.
5. If placing the queen in every column still doesn‟t lead to a solution, then we return false
6. If placing the queen in the current column leads to a solution, then we return true
7. Once we have reached the final column, we print the solution
PROGRAM :
global 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) == True: 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) == False:
print ("Solution does not exist")
OUTPUT:
0010
1000
0001
0100
RESULT:
Thus N-Queen problem using backtracking has been implemented successfully.
B) SUBSET SUM PROBLEM
AIM:
To implement subset sum problem using backtracking in python.
ALGORITHM:
1. We have a recursive function is SubsetSum(set, n, sum) that returns true if there is a subset of
set[0..n-1] with sum equal to sum.
2. We initialize the result as true.
3. If the sum is 0, we return true.
4. If n is 0 and sum is not 0, we return false.
5. If the last element is greater than sum, we ignore it.
6. If the last element is equal to sum, we return true.
7. We recur for two subproblems.
a. If we include the last element, we recur for n-1 elements and sum-set[n-1].
b. If we don‟t include the last element, we recur for n-1 elements and s , If any of the above two
cases is true, we return true. Otherwise we return false.
8. If any of the above two cases is true, we return true. Otherwise we return false.
PROGRAM:
def isSubsetSum(set, n, sum) : if (sum == 0) :
return True
if (n == 0 and sum != 0) : return False
If (set[n - 1] > sum) :
return isSubsetSum(set, n - 1, sum)
return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1]) set = [3, 34, 4, 12, 5, 2]
sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True) : print("Found a subset with given sum") else :
print("No subset with given sum")
OUTPUT:
Found a subset with given sum.
.
RESULT:
Thus Subset sum problem using backtracking has been implemented successfully.