AD3271 DSD lab mannual final copy
AD3271 DSD lab mannual final copy
AD3271 DSD lab mannual final copy
Technology
NH7, SalemMainRd, T. Kanigarahalli, Thoppur, Dharmapuri, Tamil Nadu636
NAME :
REGISTER NO :
YEAR/SEMESTER :
ACADEMIC YEAR :
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time), those who
come after 5 minutes will not be allowed into the lab.
2. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm, Procedure,
Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in the lab.
c. Proper Dress code and Identity card.
d. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted to you
by the faculty.
3. Execute your task in the laboratory, and record the results / output in the lab observation note book, and get
certified by the concerned faculty.
4. All the students should be polite and cooperative with the laboratory staff, must maintain the discipline and
decency in the laboratory.
5. Computer labs are established with sophisticated and high-end branded systems, which should be utilized
properly.
6. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab sessions with the
staff and systems etc., will attract severe punishment.
7. Students must take the permission of the faculty in case of any urgency to go out; if anybody found loitering
outside the lab / class without permission during working hours will be treated seriously and punished
appropriately.
8. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly.
9. This Observation contains the basic diagrams of the circuits enlisted in the syllabus of the CS3691
EMBEDDED SYSTEMS AND IOT course, along with the design of various components of the circuit and
controller.
10. The aim of the experiment is also given at the beginning of each experiment. Once the student can design the
circuit as per the circuit diagram, he/she is supposed to go through the instructions carefully and do the
experiments step by step.
11. They should get their observations verified and signed by the staff within two days and prepare & submit the
record of the experiment when they come to the laboratory in the subsequent week.
12. The record should contain experiment No., Date, Aim, Apparatus required, Theory, Procedure, and result on
one side (i.e., Right-hand side, where rulings are provided) and Circuit diagram, Design, Model Graphs,
Tabulations, Calculations. Pre-Lab and Post Lab questions on the other side (i.e., Left-hand side, where
black space are provided)
13. The students are directed to discuss & clarify their doubts with the staff members as and when required.
They are also directed to follow strictly the guidelines specified.
Jayalakshmi Institute of
Technology
Thoppur, Dharmapuri, Tamil Nadu 636 352.
BONAFIDE CERTIFICATE
Name: ………………………………………………………………………..
Academic Year:………………….. Semester:…………… Branch:……………….
Register No.
Certified that this is the bonafide record of work done by the above student in the
202 - 202.
MISSION
PO2: Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
PSO2: Apply cutting edge technologies and strong analytical skills to develop quality
software in scientific and business applications for the betterment of society and
Industry.
7
8
INDEX
Page Marks
S.No. Date Name of the Experiment Sign
No. Awarded
10
11
12
13
14
15
16
17
Average Marks:
9
Sample Output:
INPUT OUTPUT
10
EXP NO: 1
Write a Program to Implement the simple ADTs as Python
DATE: classes
Aim. To Implement simple ADTs as Python classes using Stack, Queue, List using python.
Algorithm:
1. Create a Stack[ ],Queue[],List[] with MAX size as your wish.
2. Write function for all the basic operations of stack, Queue, List - PUSH(), POP() and
DISPLAY(),append(),Extend().
3. Close the program
Coding :
Stack:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
11
List:
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
Output:
Stack:
Initial stack ['a',
'b', 'c']
Elements poped from stack: c
ba
Stack after elements are poped: []
Queue:
['a', 'b', 'c']
Elements dequeued from queue a
bc
Queue after removing elements []
List:
Initial List:
[1, 2, 3, 4]
List after performing Extend
Operation: [1, 2, 3, 4, 8, 'Geeks',
'Always']
12
Pre-lab questions:
MARKS ALLOCATION
Result:
Thus the Implementation of simple ADTs as Python classes was executed successfully.
13
EXP NO: 2
Write a Program to Implement the recursive algorithms in
DATE: Python
Aim:
To Implement a recursive algorithm in Python using Fibonacci Series
Algorithm:
Step 1: Input the 'n' value until which the Fibonacci series has to be generated
Step 7: sum = a + b
Coding:
No = 10
num1, num2 = 0, 1
count = 0 if No
<= 0:
print("Invalid Number") elif
No == 1:
print("Fibonacci sequence for limit of ",No,":")
print(num1)
else:
print("Fibonacci sequence:")
while count < No:
14
print(num1)
nth = num1 + num2
num1 = num2
num2 = nth
count += 1
Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
15
Pre-lab questions:
1. What is recursion?
2. What is the recursive case in a recursive function?
3. What are some advantages and disadvantages of recursion?
4. What is the base case in a recursive function?
5. How do you identify when a problem is suited for recursion?
Post Lab Questions:
MARKS ALLOCATION
Result:
Thus the Implementation of recursive algorithms in Python using Fibonacci series was executed
successfully.
16
EXP NO: 3
Write a Program to Implement List ADT using Python
DATE: arrays
Aim:
To Implement List ADT using Python arrays
Algorithm
1. Using define function initialize the list
2. while loop to declare the elements until the condition is satisfied.
3. using converter function to convert the elements to an array
Stop the program
Coding:
class node:
def init (self, data):
self.data=data
self.next=None
def add(data):
nn=node(0)
nn.data=data
nn.next=None
return nn
def
printarray(a,n):
i=0
while(i<n):
print(a[i], end = "
") i=i+1
def
findlength(head)
: cur=head
count=0
while(cur!
=None):
count=count+1
cur=cur.next
return count
def convertarr(head):
17
index=0
cur=hea
d
while(cur!=None):
arr.append(cur.data)
cur=cur.next
printarray(arr,
len) head=node(0)
head=add(6)
head.next = add(4)
head.next.next = add(3)
head.next.next.next = add(4)
convertarr(head)
Output:
[6,4,3,4]
[6 4 3 4]
18
Pre-lab questions:
MARKS ALLOCATION
Result:
Thus the implementation of List in arrays was executed successfully.
19
EXP NO: 4
Write a Program to Linked list implementations of List
DATE:
Aim:
To Implement the Linked list implementations of List using python
Algorithm:
1. Create a list[ ] with MAX size as your wish.
2. Write function for all the basic operations of list - create(), insert(), deletion(), display().
3. Using append() to extend the elements, removal() to delete the elements
Close the program
Coding:
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
List = [] print("Blank
List: ") print(List)
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ") print(List[0])
print(List[2])
#Adding the elements:
List = [1,2,3,4]
print("Initial List: ")
print(List) List.insert(3,
12) List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
20
print(List)
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]
>>>
===================== RESTART: Z:/New folder/queue 1.py
=====================
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['Geeks', 1, 2, 3, 12, 4]
>>>
===================== RESTART: Z:/New folder/queue 1.py
=====================
Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
Pre-lab questions:
21
1. What is a Linked List?
2. What are the main types of Linked Lists?
3. How is a Linked List different from an array or an array-based list?
4. What are the advantages and disadvantages of Linked Lists?
5. What is the difference between singly linked lists and doubly linked lists?
MARKS ALLOCATION
Result:
Thus the list was created, inserted, removed and extend the element was executed successfully.
EXP NO: 5
22
DATE:
Write a Program to Implementation of Stack and Queue
ADTs
Aim:
To Implementation of Stack and Queue ADTs
Algorithm:
Coding:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
23
Output:
Initial stack ['a', 'b', 'c']
Elements poped from stack:
cba
Stack after elements are poped: []
24
Pre-lab questions:
MARKS ALLOCATION
Result:
Thus the program was executed successfully
25
EXP NO: 6 a Write a Program to implement the Application of List
DATE: using Polynomial Addition in python
Aim:
To implement list application using Polynomial Addition in python
Algorithm:
1. Using the define function intial elements will be declared.
2. for loop gives the output of sum of the elements
3. print[poly] statement have the sum of two polynomial elements.
4. Close the program
Coding:
Output:
Student Grades List:
John: 85
Alice: 90
Bob: 78
Sarah: 92
Michael: 88
27
Students sorted by grade (ascending):
Bob: 80
John: 85
Michael: 88
Sarah: 92
Emma: 95
28
Pre-lab questions:
3. Can Lists be used to simulate real-world systems, such as a to-do list or a customer
queue?
4. How can Lists be used to represent matrix operations, and what are the
advantages of doing so?
5. How can you optimize List operations when dealing with large datasets?
MARKS ALLOCATION
Result:
Thus the program was executed successfully.
EXP NO: 6 b
29
DATE:
Write a Program to implement the Application of Stack
Aim:
To implement the conversion of infix to postfix in stack
Algorithm:
1. Read the given expression
2. check ifempty or not ,the stack will insert the elements.
3. Using push(),pop() to insert the element or remove the element.
4. Check the operator based on the precedence the expression will be evaluated
5. Close the program
Coding:
class Conversion:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = [] # stack to store operators
self.output = [] # list to store postfix expression
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
Output:
abcd^e-fgh*+^*+i-
Pre-lab questions:
1. What is a Stack ADT, and how is it different from other data structures?
31
2. What are the main operations of a Stack?
3. What are the practical applications of Stacks in real-world programming?
4. What is the role of a stack in the Undo/Redo feature in applications?
5. Why are stacks used for parsing expressions in compilers or calculators?
MARKS ALLOCATION
Result:
Aim:
To implement the application of queue using FCFS CPU Scheduling
32
Algorithm:
1. Input the number of processes required to be scheduled using FCFS, burst time for each
process and its arrival time.
2. Calculate the Finish Time, Turn Around Time and Waiting Time for each process which
in turn help to calculate Average Waiting Time and Average Turn Around Time required
by CPU to schedule given set of process using FCFS.
a.
for i = 0, Finish Time T 0 = Arrival Time T 0 + Burst Time T 0
b.
for i >= 1, Finish Time T i = Burst Time T i + Finish Time T i - 1
c.
for i = 0, Turn Around Time T 0 = Finish Time T 0 - Arrival Time T 0
d.
for i >= 1, Turn Around Time T i = Finish Time T i - Arrival Time T i
e.
for i = 0, Waiting Time T 0 = Turn Around Time T 0 - Burst Time T 0
f.
for i >= 1, Waiting Time T i = Turn Around Time T i - Burst Time T i - 1
3. Process with less arrival time comes first and gets scheduled first by the CPU.
4. Calculate the Average Waiting Time and Average Turn Around Time.
5. Stop the program
Coding:
def findWaitingTime(processes, n,bt, wt):
wt[0] = 0
for i in range(1, n ):
wt[i] = bt[i - 1] + wt[i - 1]
turnaround
# time by adding bt[i] + wt[i]
for i in range(n): tat[i] =
bt[i] + wt[i]
wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0 findWaitingTime(processes, n, bt, wt)
33
for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
print(" " + str(i + 1) + "\t\t" +str(bt[i]) + "\t "
str(wt[i]) + "\t\t " +str(tat[i]))
processes = [ 1, 2, 3] n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time)
Output:
`Processes Burst Time Waiting Time Turnaround Time
1 10 0 10
2 5 10 15
3 8 15 23
Average Waiting Time = 8.333333333333334
Average Turnaround Time = 16.0
Pre-lab questions:
MARKS ALLOCATION
Result:
Thus the FCFS CPU Scheduling was Executed Successfully.
Aim:
To implement searching using Linear and Binary Search algorithm using python.
Algorithm:
Linear Search:
1. Read the search element from the user
2. Compare, the search element with the first element in the list
3. If both are matching, then display "Given element found!!!" and terminate the function
35
4. If both are not matching, then compare search element with the next element in the list.
5. Repeat steps 3 and 4 until the search element is compared with the last element in the list.
6. If the last element in the list is also doesn't match, then display "Element not found!!!" and
terminate the function.
Binary search :
1. Read the search element from the user
2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!" and terminate the function
5. If both are not matching, then check whether the search element is smaller or larger
than middle element
6. If the search element is smaller than middle element, then repeat steps 2, 3, 4 and 5 for the
left sublist of the middle element.
7. If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
8. Repeat the same process until we find the search element in the list or until sublist
contains only one element.
9. If that element also doesn't match with the search element, then display "Element not found
in the list!!!" and terminate the function.
else:
return -1
arr = [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ]
key = 40
result = BinarySearch(arr, 0, len(arr)-1, key) if
result != -1:
print(key, "Found at index", str(result))
else:
print(key, "not Found")
Result:
Thus, the implementation of searching using Linear and Binary Search using python was
executed successfully
Aim:
To Implement sorting Algorithm using Quick Sort and Insertion Sort algorithm using python
Algorithm:
Quick Sort:
1. Find a “pivot” item in the array. This item is the basis for comparison for a single
round.
2. Start a pointer (the left pointer) at the first item in the array.
3. Start a pointer (the right pointer) at the last item in the array.
4. While the value at the left pointer in the array is less than the pivot value, move the
left pointer to the right (add 1). Continue until the value at the left pointer is greater
37
than or equal to the pivot value.
5. While the value at the right pointer in the array is greater than the pivot value, move the
right pointer to the left (subtract 1). Continue until the value at the right pointer is less
than or equal to the pivot value.
6. If the left pointer is less than or equal to the right pointer, then swap the values at
these locations in the array.
7. Move the left pointer to the right by one and the right pointer to the left by one.
Insertion Sort:
arr[i + 1], arr[high] = arr[high], arr[i + 1] # swap pivot with the element at i+1
return (i + 1) # return pivot index
# QuickSort function
def quickSort(arr, low, high):
if low < high:
pi = partition(arr, low, high) # partitioning index
quickSort(arr, low, pi - 1) # sort the left subarray
quickSort(arr, pi + 1, high) # sort the right subarray
# Test QuickSort
arr1 = [2, 5, 3, 8, 6, 5, 4, 7]
n = len(arr1)
quickSort(arr1, 0, n - 1)
print("QuickSort Sorted array is:")
for i in range(n):
print(arr1[i], end=" ")
print() # Add a new line
for i in range(len(arr2)):
print(arr2[i], end=" ")
39
Output:
Pre-lab questions:
1. What is the time complexity of Quick Sort in the average and worst-case scenarios?
2. How does the Quick Sort algorithm work, and what is its partitioning step?
3. Why is Quick Sort considered efficient on average, despite its worst-case time
complexity?
4. What are the benefits and drawbacks of using Insertion Sort for small datasets?
5. What type of data structure is best suited for Quick Sort, and why is it more
efficient with certain types of data (e.g., partially sorted data)?
MARKS ALLOCATION
Result:
Thus, the implementation of searching Quick and Insertion Sort algorithm using python was
executed successfully.
EXP NO: 8
Write a Program to Implement of Hash tables
DATE:
Aim:
To Implement the Hash tables using python.
Algorithm:
1. Create a structure, data (hash table item) with key and value as data.
2. for loops to define the range within the set of elements.
3.hashfunction(key) for the size of capacity
4. Using insert (), removal () data to be presented or removed.
5. Stop the program
Coding:
# Function to get the next prime number greater than the given number
def getPrime(n):
if n % 2 == 0:
n += 1 # Start from the next odd number if n is even
while not checkPrime(n):
n += 2 # Check only odd numbers
return n
Pre-lab questions:
4. What are the key differences between hash tables and arrays or lists?
5. What are the advantages and disadvantages of hash tables compared to other
data structures like trees or lists?
1. Compare the performance of hash tables with binary search trees. In what scenarios
would one be preferred over the other?
2. What happens if two keys produce the same hash value (i.e., a hash collision)?
3. What is the space complexity of a hash table? How does the size of the table
impact its performance?
4. How does a hash table handle deletion of an element?
5. Why is it important to choose a good hash function, and how can a poor hash function
affect performance?
43
MARKS ALLOCATION
Result:
Thus, the Implementation of hashing was executed successfully
EXP NO: 9 a
Write a Program to Implement Tree representation
DATE:
Aim:
To implement tree representation in binary tree format
Algorithm:
1. Create a binary tree.
2. Initially all the left and right vertex are none, then declare the values using insert ()
function.
3. If data>right element place the element in right
4. If data<left element place the element in left
5. print the tree
6. Stop the program
Coding:
45
Output:
In-order traversal of the tree:
3 6 12 14
Result:
Thus, the binary tree was successfully created
EXP NO: 9 b
Write a Program to Implement Tree Traversal Algorithms
DATE:
Aim:
To Implement traversal using In order, Preorder,Postorder techniques.
Algorithm:
In order(tree)
1. Traverse the left subtree, i.e., call In order(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call In order(right-
subtree) Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-
subtree) Post order(tree)
1. Traverse the left subtree, i.e., call Post order(left-subtree)
2. Traverse the right subtree, i.e., call Post order(right-subtree)
Coding:
if root:
print(root.val, end=" ") # Print root node
printPreorder(root.left) # Traverse left subtree
printPreorder(root.right) # Traverse right subtree
47
Output:
Preorder traversal of binary tree is
12453
In order traversal of binary tree is
42513
Post order traversal of binary tree is
45231
48
Result:
Thus the Implementation of traversal using In order, Preorder,Postorder techniques was executed
successfully
Pre-lab questions:
1. How would you implement a tree traversal that visits each node in both pre-order
and post-order sequentially?
2. Compare the use cases of pre-order traversal vs. post-order traversal in
practical applications like expression evaluation or tree construction.
3. In a binary search tree (BST), what would be the output of an in-order traversal?
Why is this important?
4. How can tree traversal be used in evaluating expressions in a tree (e.g., in a binary
expression tree)?
5. What is the space complexity of each tree traversal method (in-order, pre-order,
post-order)?
MARKS ALLOCATION
EXP NO: 10
Write a Program to Implementation of Binary Search
DATE: Trees
Aim:
To Implement the Binary Search Trees using python.
Algorithm:
Step 2 - Compare the search element with the value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate the function
Step 4 - If both are not matched, then check whether search element is smaller or larger than
that node value.
Step 5 - If search element is smaller, then continue the search process in left subtree.
Step 6- If search element is larger, then continue the search process in right subtree.
Step 7 - Repeat the same until we find the exact element or until the search element is compared
with the leaf node
Step 8 - If we reach to the node having the value equal to the search value then display "Element
is found" and terminate the function.
Coding:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
Output:
7 Not Found
51
Pre-lab questions:
1. What is a Binary Search Tree (BST), and what are its properties?
2. How does the insertion process work in a Binary Search Tree?
3. What is the time complexity of searching, inserting, and deleting nodes in a Binary
Search Tree?
4. Explain the difference between a balanced and an unbalanced BST. How does
balance affect performance?
5. What are the advantages of using a BST over an unsorted array or list for search
operations?
MARKS ALLOCATION
Result:
Thus, the Implementation of B i n a r y Search Trees using python was executed successfully.
EXP NO: 10
52
DATE: Write a Program to Implementation of Heaps
Aim:
To Implement the Heap algorithm using python.
Algorithm:
1. Insert the heap function in the list
2. using heap push(),heap pop(),heap ify() to insert ,delete, display the elements.
3. Stop the program
Coding:
import heapq
Output:
Pre-lab questions:
1. What is a heap, and how does it differ from a binary search tree (BST)?
53
2. What are the properties of a max heap and a min heap?
3. How does the heap property affect the structure of a heap?
4. Explain how the heap insertion process works
5. What is the time complexity for insertion and deletion in a heap?
1. What are the advantages of using a heap over other data structures like arrays or
linked lists?
2. How does the time complexity of heap operations (insert, delete, and extract-
max/min) compare to other data structures like balanced trees or arrays?
3. In heapsort, what is the role of the heapify operation in sorting the array?
4. Explain how you can efficiently build a heap from an unsorted array.
5. How can you implement a heap using a dynamic array (list in Python)?
MARKS ALLOCATION
Result:
Thus, the Implementation of the Heap algorithm was executed successfully.
EXP NO: 12 a
Write a Program to Implement the Graph representation
DATE:
Aim:
54
To implement the graph representation using python
Algorithm:
1. Initialize Graph: Create a matrix of size V x V (where V is the number of vertices) and
initialize all elements to 0. This represents that initially, there are no edges between any
vertices
2. Add Edge: To add an edge between two vertices u and v, set adj_matrix[u][v] = 1 for an
unweighted graph (or the edge weight if it's a weighted graph).
3. Remove Edge: To remove an edge between two vertices u and v, set adj_matrix[u][v] =
0.
4.. Display Graph: Print the matrix to show the adjacency matrix representation of the
graph.
class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
g = Graph(graph_elements)
print(g.getVertices())
class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def edges(self):
return self.findedges()
def findedges(self):
edgename = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
55
if {nxtvrtx, vrtx} not in edgename: # Prevents duplicate edges
edgename.append({vrtx, nxtvrtx})
return edgename
g = Graph(graph_elements)
print(g.edges())
Output:
DISPLAYING VERTICES
['a', 'b', 'c', 'd', 'e']
DISPLAYING EDGES
[{'a', 'b'}, {'a', 'c'}, {'d', 'b'}, {'c', 'd'}, {'d', 'e'}]
Result:
Thus, the implementation of graphs was executed successfully.
Aim:
To Implement using BFS, DFS can be traversed.
Algorithm:
56
DFS:
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the
Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack
and push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top
of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the
stack.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph
BFS:
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and
insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queue
then delete that vertex.
Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges
from the graph
Coding:
BFS
import collections
while queue:
vertex = queue.popleft()
print(str(vertex) + " ", end="")
57
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
DFS Coding:
ef dfs_recursive(graph, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
dfs_recursive(graph, neighbor, visited)
# Example graph
graph = {
'A': ['B', 'C', 'D'],
'B': ['A', 'E'],
'C': ['A', 'F'],
'D': ['A', 'F'],
'E': ['B', 'J'],
Output:
DFS Recursive Traversal:
ABEJHIGFCDK
Pre-lab questions:
1. What is the difference between Depth-First Search (DFS) and Breadth-First Search
(BFS)?
2. How does DFS use a stack to traverse a graph?
3. How does BFS use a queue to traverse a graph?
4. What are the advantages of DFS over BFS, and vice versa?
5. How can you implement DFS using recursion?
MARKS ALLOCATION
Result:
Thus the implementation of using BFS,DFS graph can be traversed.
Aim:
To Implement single source shortest path algorithm using Bellman Ford Algorithm.
Algorithm:
1) This step initializes distances from source to all vertices as infinite and distance to source
itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is
source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of
vertices in given graph.
a) Do following for each edge u-v
If dist[v] > dist[u] + weight of edge uv, then update dist[v] dist[v]
= dist[u] + weight of edge uv 60
3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v
If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative
weight cycle. If we iterate through all edges one more time and get a shorter path for any
vertex, then there is a negative weight cycle
Coding:
return
# Step 4: Print the distance array.
print("Vertex Distance from Source")
for i in range(V):
print(f"{i}\t\t{dis[i]}")
# Driver Code
if __name__ == "__main__":
V = 5 # Number of vertices in graph
E = 8 # Number of edges in graph
graph = [
[0, 1, -1], # Edge 0->1 with weight -1
[0, 2, 4], # Edge 0->2 with weight 4
[1, 2, 3], # Edge 1->2 with weight 3
[1, 3, 2], # Edge 1->3 with weight 2
[1, 4, 2], # Edge 1->4 with weight 2
[3, 2, 5], # Edge 3->2 with weight 5
[3, 1, 1], # Edge 3->1 with weight 1
[4, 3, -3] # Edge 4->3 with weight -3
61
]
BellmanFord(graph, V, E, 0)
OUTPUT:
Pre-lab questions:
1. What is the Bellman-Ford algorithm and how does it differ from Dijkstra’s algorithm?
2. How does the Bellman-Ford algorithm handle negative weights in a graph?
3. What is the time complexity of the Bellman-Ford algorithm?
4. What is a negative weight cycle and how does Bellman-Ford detect it?
5. What is the main advantage of using the Bellman-Ford algorithm over other shortest path
algorithms?
Post Lab Questions:
1. Explain how the Bellman-Ford algorithm detects negative weight cycles in a graph.
2. What are the practical applications of the Bellman-Ford algorithm?
3. Can Bellman-Ford work with both directed and undirected graphs?
4. What is the role of the 'relaxation' step in the Bellman-Ford algorithm?
5. How can the Bellman-Ford algorithm be optimized to run faster in some cases?
62
MARKS ALLOCATION
Result:
Thus, the Implementation of single source shortest path algorithm was executed successfully.
Aim:
To implement the minimum spanning tree algorithms using Kruskal Algorithm.
Algorithm:
1. Label each vertex
2. List the edges in non-decreasing order of weight.
3. Start with the smallest weighted and beginning growing the minimum weighted spanning
tree from this edge.
4. Add the next available edge that does not form a cycle to the construction of the minimum
weighted spanning tree. If the addition of the next least weighted edge forms a cycle, do not use
it.
5. Continue with step 4 until you have a spanning tree.
Coding:
63
class Graph:
def __init__(self, vertices):
self.V = vertices # Number of vertices
self.graph = [] # List to store the graph edges
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
# If u and v are not connected (not forming a cycle), include the edge
if x != y:
e=e+1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
g.add_edge(1, 2, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 4, 3)
g.add_edge(4, 5, 3)
65
Output:
Pre-lab questions:
MARKS ALLOCATION
Result:
Thus, the program was executed successfully.
Aim:
To implement the Binary search algorithm using python.
Algorithm:
67
1. Initial Setup: Given a sorted array and a target value, set the low and high bounds for
the search (initially low = 0 and high = len(array) - 1).
2. Repeat until the target is found or the bounds cross:
Calculate the middle index: mid = (low + high) // 2.
Compare the target with the element at mid:
o If the target is equal to the element at mid, return mid (index of the target).
o If the target is smaller than the element at mid, narrow the search to the lower
half by setting high = mid - 1.
o If the target is larger than the element at mid, narrow the search to the upper half
by setting low = mid + 1.
3. If the target is not found and the search interval becomes invalid (low > high), return -1
to indicate that the target is not in the list.
Coding:
# Example usage:
arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # Sorted array
68
target = 14 # Target to search for
if result != -1:
print(f"Element found at index {result}")
else:
Output:
Pre-lab questions:
1. What is the purpose of the Binary Search algorithm, and how does it differ from a
linear search?
2. Why is Binary Search applicable only to sorted arrays or lists? Explain the reasoning
behind this requirement.
3. What is the time complexity of the Binary Search algorithm, and how does it
compare to the time complexity of a linear search?
4. How does the Binary Search algorithm narrow down the search space during
each iteration?
69
5. What are the advantages and disadvantages of using Binary Search over other
search algorithms?
1. Explain how the Binary Search algorithm ensures efficiency by reducing the
problem size in each step.
2. What happens if you try to use Binary Search on an unsorted array? What issues
would arise?
4. What would be the effect of not checking the condition low <= high in the Binary
Search loop?
5. Can you implement Binary Search recursively instead of iteratively? If so, how would
the recursive approach differ from the iterative version?
MARKS ALLOCATION
Result:
Thus , the program was executed successfully.
70