Daa Record Ai
Daa Record Ai
DATE:
AIM:
To Implement a python program for recursive algorithm.
PROCEDURE:
(FACTORIAL)
STEP 1: start
STEP 5: Stop
Factorial(n)
STEP 2: Else
Fact=n=factorial(n-1)
1
PROGRAM
def factorial(n):
if n<=1:
return 1
else:
return n*factorial(n-1)
num = 5;
print("Factorial of",num,"is",factorial(num))
2
OUTPUT:
Factorial of 5 is 20
RESULT
3
EXP NO: 1 (b) IMPLEMENT NON- RECURSIVE ALGORITHM
DATE:
AIM:
To Implement a python program for Non-Recursive algorithm.
PROCEDURE:
print pos
go to step 6
else
STEP 5: if pos = -1
STEP 6: exit.
4
PROGRAM
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
if result != -1:
print("Element is present at index % d" % result)
else:
5
OUTPUT
RESULT
6
EXP NO:2 DECREASE AND CONQUER - TOPOLOGICAL SORTING
DATE:
AIM:
PROCEDURE:
STEP 1: Start
STEP 3: Remove all the edges from that vertex that go outward
STEP 4: Add that vertex to the array representing topological sorting of the graph.
STEP 6: Stop.
7
PROGRAM
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
stack.append(v)
def topological_sort(self):
visited = [False] * self.V
stack = []
for i in range(self.V):
if not visited[i]:
self.topological_sort_util(i, visited, stack)
return stack[::-1]
# Example Usage:
g = Graph(6)
8
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)
9
OUTPUT
[5, 4, 2, 3, 1, 0]
RESULT
10
EXP NO:3 TRANSFORM AND CONQUER - HEAP SORT
DATE:
AIM:
To implement the heap sort algorithm using a Transform and Conquer approach.
PROCEDURE:
STEP 2: At this point, the maximum element is stored at the root of the heap.
Replace it with the last item of the heap followed by reducing the size of the
STEP 3: Repeat step 2 while the size of the heap is greater than 1.
11
PROGRAM
def heapify(arr, n, i):
largest = i
left_child = 2 * i + 1
right_child = 2 * i + 2
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
# Example Usage:
arr = [12, 11, 13, 5, 6, 7]
print("Original array:", arr)
heap_sort(arr)
print("Sorted array:", arr)
12
OUTPUT
RESULT
13
EXP NO:4 DYNAMIC PROGRAMMING – COIN CHANGE PROBLEM
DATE:
AIM:
To implement Coin change problem using Dynamic programming.
PROCEDURE:
STEP 1: Start.
STEP 5: Define one array called dp, of size amount + 1, and fill this with -1.
STEP 6: for i in range coins array. if i > length of dp – 1, then skip the next part, go
for the next iteration. dp[i] := 1.
STEP 8: Stop
14
PROGRAM
class Solution(object):
if amount == 0 :
return 0
return -1
for i in coins:
if i > len(dp) - 1:
continue
dp[i] = 1
if dp[j - i] == -1:
continue
dp[j] = dp[j - i] + 1
else:
return dp[amount]
ob1 = Solution()
15
print(ob1.coinChange([1,2,5],amt))
OUTPUT
RESULT
Thus the program for Coin changing problem was executed successfully
16
EXP NO:5 DYNAMIC PROGRAMMING – FLOYD-WARSHALL
DATE:
AIM:
To implement Floyd-Warshall Algorithm algorithm using Dynamic programming.
PROCEDURE:
STEP 1: Start
STEP 4: for k = 1 to n
STEP 5: for i = 1 to n
STEP 6: for j = 1 to n
STEP 8: Return A
STEP 9: Stop
17
PROGRAM
def floyd_warshall(graph):
n = len(graph)
# Initialize the distance matrix with the graph's adjacency matrix
dist = [row[:] for row in graph]
return dist
# Example Usage:
# Here, 'inf' represents infinity or unreachability, and 0 represents no distance (vertex
to itself).
graph = [
[0, 1, float('inf'), 1],
[1, 0, 1, float('inf')],
[float('inf'), 1, 0, 1],
[1, float('inf'), 1, 0]
]
result = floyd_warshall(graph)
18
OUTPUT
[0, 1, 2, 1]
[1, 0, 1, 2]
[2, 1, 0, 1]
[1, 2, 1, 0]
RESULT
19
EXP NO:6 DYNAMIC PROGRAMMING – KNAPSACK PROBLEM
DATE:
AIM:
To implement Knapsack problem using Dynamic programming.
PROCEDURE:
STEP 1: Start
STEP 5: Do the following for every item “i” in the sorted order.
STEP 6: If the weight of the current item is less than or equal to the remaining
capacity then add the value of that item into the result.
STEP 7: Else add the current item as much as we can and break out of the loop.
STEP 9: Stop
20
PROGRAM
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)
21
OUTPUT
220
RESULT
22
EXP NO:7 GREEDY TECHNIQUE – DIJKSTRA’S ALGORITHM
DATE:
AIM:
To develop a program to find the shortest paths to other vertices using Djikstra’s
algorithm for the given vertex in a weighted connected graph.
PROCEDURE:
STEP 1: Start
STEP 2: Create a set that keeps track of vertices included in the shortest-path tree.
STEP 3: Assign a distance value to all vertices in the input graph. Initialize all distance values
as infinite. Assign the distance value as 0 for the source vertex so that it is picked
first.
STEP 4: While a set doesn’t include all vertices, pick a vertex u which is not there in and
STEP 7: To update the distance values, iterate through all adjacent vertices.
STEP 8: For every adjacent vertex v, if sum of the distance value of u (from source) and
weight of edge u-v, is less than the distance value of v, then update the distance
value of v.
STEP 9: Stop
23
PROGRAM
import heapq
while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)
# If the new distance is shorter, update the distance and enqueue the neighbor
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
24
# Example Usage:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
print(f"Shortest distances from node {start_node}: {shortest_distances}")
25
OUTPUT
RESULT
26
EXP NO:8 GREEDY TECHNIQUE – HUFFMAN TREES AND CODES
DATE:
AIM:
To implement Huffman Trees and Codes using Greedy technique.
PROCEDURE:
STEP 1: Start
STEP 2: Input is an array of unique characters along with their frequency of occurrences
STEP 3: Create a leaf node for each unique character and build a min heap of all leaf nodes
(Min Heap is used as a priority queue. The value of frequency field is used to compare two
STEP 4: Extract two nodes with the minimum frequency from the min heap.
STEP 6: Create a new internal node with a frequency equal to the sum of the two node
frequencies. Make the first extracted node as its left child and the other extracted node as its
STEP 7: Repeat steps 2 and 3 until the heap contains only one node. The remaining node is
STEP 8: Stop.
27
PROGRAM
import heapq
from collections import Counter
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def build_huffman_tree(data):
frequency = Counter(data)
heap = [HuffmanNode(char, freq) for char, freq in frequency.items()]
heapq.heapify(heap)
heapq.heappush(heap, internal_node)
return heap[0]
return decoded_data
# Example Usage:
data = "ABRACADABRA"
root = build_huffman_tree(data)
codes = {}
29
build_huffman_codes(root, "", codes)
encoded_data = huffman_encode(data, codes)
decoded_data = huffman_decode(encoded_data, root)
30
OUTPUT
Huffman Codes:
A: 0
B: 10
R: 110
C: 1110
D: 1111
RESULT
Thus the program for Huffman trees and codes was executed successfully
31
EXP NO:9 BACKTRACKING – N-QUEEN PROBLEM
DATE:
AIM:
To implement N-Queen Problem usimg Backtracking.
PROCEDURE:
a) If the queen can be placed safely in this row, then mark this [row, column] as part of the
b) If placing the queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack)
STEP 4: If all rows have been tried and nothing worked, return false to trigger backtracking.
32
PROGRAM
return True
for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 1
33
# Backtrack: Remove the queen if the placement doesn't lead to a solution
board[i][col] = 0
def solve_nqueens(n):
board = [[0] * n for _ in range(n)]
solutions = []
solve_nqueens_util(board, 0, n, solutions)
return solutions
# Example Usage:
n=4
solutions = solve_nqueens(n)
34
OUTPUT
Solution 1:
.Q..
...Q
Q...
..Q.
Solution 2:
..Q.
Q...
...Q
.Q..
RESULT
35
EXP NO:10 BACKTRACKING – SUBSET SUM PROBLEM
DATE:
AIM:
To implement Subset Sum Problem using backtracking.
PROCEDURE:
STEP 2: Add the next element from the list to the set.
STEP 3: If the subset is having sum M, then stop with that subset as solution.
STEP 4: If the subset is not feasible or if we have reached the end of the set, then backtrack
STEP 6: If we have visited all the elements without finding a suitable subset and if no
36
PROGRAM
# Example Usage:
nums = [2, 3, 7, 8, 10]
target_sum = 10
solutions = subset_sum(nums, target_sum)
print(f"Original Set: {nums}")
print(f"Target Sum: {target_sum}")
print("Subset Sums:")
for solution in solutions:
37
print(solution)
OUTPUT
RESULT
38
EXP NO:11 BRANCH AND BOUND - ASSIGNMENT PROBLEM
DATE:
AIM:
To implement Assignment Problem using Branch and Bound technique.
PROCEDURE:
STEP 1: Start
STEP 2: Get the input data.
STEP 3: Constraints:
a) Each worker is assigned to at most 1 task.
b) Each task is assigned to exactly one worker.
STEP 4: Solve the problem.
STEP 5: Print the solution.
39
PROGRAM
import numpy as np
class AssignmentProblem:
def __init__(self, cost_matrix):
self.cost_matrix = np.array(cost_matrix)
self.n = len(cost_matrix)
self.row_reduction()
self.column_reduction()
self.marked_rows = [False] * self.n
self.marked_columns = [False] * self.n
self.assignment = [-1] * self.n
self.total_cost = 0
def row_reduction(self):
for i in range(self.n):
min_val = min(self.cost_matrix[i])
self.cost_matrix[i] -= min_val
def column_reduction(self):
for j in range(self.n):
min_val = min(self.cost_matrix[:, j])
self.cost_matrix[:, j] -= min_val
def find_minimal_zeros(self):
min_val = float('inf')
for i in range(self.n):
for j in range(self.n):
if not self.marked_rows[i] and not self.marked_columns[j]:
if self.cost_matrix[i, j] == 0 and min_val > 0:
min_val = self.cost_matrix[i, j]
min_zero_position = (i, j)
return min_zero_position if min_val < float('inf') else None
40
def mark_zeros(self, row, col):
for i in range(self.n):
if self.cost_matrix[i, col] == 0:
self.marked_rows[i] = True
for j in range(self.n):
if self.cost_matrix[row, j] == 0:
self.marked_columns[j] = True
def unmark_all(self):
self.marked_rows = [False] * self.n
self.marked_columns = [False] * self.n
def find_optimal_assignment(self):
while None in self.assignment:
zero_position = self.find_minimal_zeros()
if zero_position is None:
break
row, col = zero_position
self.assign_job(row, col)
self.row_reduction()
self.column_reduction()
self.unmark_all()
for i in range(self.n):
self.total_cost += self.cost_matrix[i, self.assignment[i]]
# Example Usage:
cost_matrix = [
41
[9, 11, 14, 11],
[6, 15, 13, 13],
[12, 13, 5, 6],
[5, 6, 9, 10]
]
assignment_problem = AssignmentProblem(cost_matrix)
assignment, total_cost = assignment_problem.find_optimal_assignment()
42
OUTPUT
RESULT
43
EXP NO:12 BRANCH AND BOUND - TRAVELING SALESMAN PROBLEM
DATE:
AIM:
To implement Travelling Salesman Problem using Branch and Bound technique.
PROCEDURE:
44
PROGRAM
import numpy as np
class TravelingSalesmanProblem:
def __init__(self, distance_matrix):
self.n = len(distance_matrix)
self.distance_matrix = np.array(distance_matrix)
self.visited = set()
self.best_path = None
self.best_cost = np.inf
def find_optimal_route(self):
# Start with the first city
initial_path = [0]
initial_cost = 0
# Example Usage:
distance_matrix = [
[np.inf, 2, 9, 10],
[1, np.inf, 6, 4],
[15, 7, np.inf, 8],
[6, 3, 12, np.inf]
]
tsp_problem = TravelingSalesmanProblem(distance_matrix)
optimal_route, optimal_cost = tsp_problem.find_optimal_route()
print("Optimal Route:", optimal_route)
print("Optimal Cost:", optimal_cost)
46
OUTPUT
RESULT
Thus the program for Travelling Salesman problem was executed successfully
47