AD3271 Coding and Output
AD3271 Coding and Output
Coding :
Stack:
# Initialize an empty stack
stack = []
# Append elements to the stack
stack.append('a')
stack.append('b')
stack.append('c')
# Print the initial stack
print('Initial stack:')
print(stack)
# Pop elements from the stack
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
# Print the stack after popping elements
print('\nStack after elements are popped:')
print(stack)
Queue
# Initialize an empty queue
queue = []
# Append elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
# Print the initial queue
print("Initial queue:")
print(queue)
# Dequeue elements from the queue
print("\nElements dequeued from queue:")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
# Print the queue after removing elements
print("\nQueue after removing elements:")
print(queue)
List:
# Initialize a list
List = [1, 2, 3, 4]
# Print the initial list
print("Initial List:")
print(List)
# Extend the list with additional elements
List.extend([8, 'Geeks', 'Always'])
# Print the list after performing the extend operation
print("\nList after performing Extend Operation:")
print(List)
OUTPUT:
Stack:
Initial stack:
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Queue:
Initial queue:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Geeks', 'Always']
EX.NO:2 IMPLEMENT RECURSIVE ALGORITHMS IN PYTHON
Coding :
# Number of terms to generate in the Fibonacci sequence
No = 10
# Initializing the first two numbers in the sequence
num1, num2 = 0, 1
# Counter to keep track of the number of terms generated
count = 0
# Check if the number of terms is valid
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:
print(num1)
nth = num1 + num2
# Update values of num1 and num2
num1 = num2
num2 = nth
count += 1
OUTPUT
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
EX.NO:3 IMPLEMENT LIST ADT USING PYTHON ARRAYS
Coding :
class Node:
def __init__(self, data):
self.data = data
self.next = None
def add(data):
nn = Node(data)
return nn
def print_array(arr, n):
for i in range(n):
print(arr[i], end=" ")
print()
def find_length(head):
cur = head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def convert_to_array(head):
length = find_length(head)
arr = []
cur = head
while cur is not None:
arr.append(cur.data)
cur = cur.next
print_array(arr, length)
# Create and populate the linked list
head = add(6)
head.next = add(4)
head.next.next = add(3)
head.next.next.next = add(4)
# Convert linked list to array and print it
convert_to_array(head)
OUTPUT
6434
EX.NO:4 LINKED LIST IMPLEMENTATIONS OF LIST
Coding :
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Initial List:
[1, 2, 3, 4]
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
EX.NO:5 IMPLEMENTATION OF STACK AND QUEUE ADTs
Coding :
Stack:
Queue
# Initialize an empty queue
queue = []
# Append elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
# Print the initial queue
print("Initial queue:")
print(queue)
# Dequeue elements from the queue
print("\nElements dequeued from queue:")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
# Print the queue after removing elements
print("\nQueue after removing elements:")
print(queue)
OUTPUT:
Stack:
Initial stack:
['a', 'b', 'c']
Queue:
Initial queue:
[]
EX.NO:6A APPLICATION OF LIST
Coding:
def add(A, B, m, n):
size = max(m, n)
sum_poly = [0 for i in range(size)])]
# Add coefficients of A to sum_poly
for i in range(m):
sum_poly[i] = A[i]
# Add coefficients of B to sum_poly
for i in range(n):
sum_poly[i] += B[i]
return sum_poly
def printPoly(poly, n):
for i in range(n):
print(poly[i], end="")
if i != 0:
print("x^", i, end="")
if i != n - 1:
print(" + ", end="")
print() # For a new line after printing the polynomial
if __name__ == '__main__':
A = [5, 0, 10, 6]
B = [1, 2, 4]
m = len(A)
n = len(B)
OUTPUT
First polynomial is:
5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is:
1 + 2x^1 + 4x^2
Sum polynomial is:
6 + 2x^1 + 14x^2 + 6x^3
EX.NO:6B APPLICATION OF STACK
CODING:
class Conversion:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
def isEmpty(self):
return self.top == -1
def peek(self):
return self.array[-1]
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
def push(self, op):
self.top += 1
self.array.append(op)
def isOperand(self, ch):
return ch.isalpha()
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False
def infixToPostfix(self, exp):
for i in exp:
if self.isOperand(i):
self.output.append(i)
elif i == '(':
self.push(i)
elif i == ')':
while not self.isEmpty() and self.peek() != '(':
a = self.pop()
self.output.append(a)
if not self.isEmpty() and self.peek() != '(':
return -1
else:
self.pop()
else:
while not self.isEmpty() and self.notGreater(i):
self.output.append(self.pop())
self.push(i)
OUTPUT
abcd^e-fgh*+^*+i-
EX.NO:6C APPLICATION OF QUEUE
CODING:
def findWaitingTime(processes, n, bt, wt):
# waiting time for first process is 0
wt[0] = 0
# calculating waiting time for each process
for i in range(1, n):
wt[i] = bt[i - 1] + wt[i - 1]
def findTurnAroundTime(processes, n, bt, wt, tat):
# calculating turnaround time by adding burst time and waiting time
for i in range(n):
tat[i] = bt[i] + wt[i]
def findavgTime(processes, n, bt):
wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0
# Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt)
# Function to find turn around time for all processes
findTurnAroundTime(processes, n, bt, wt, tat)
# Display processes along with all details
print("Processes Burst time Waiting time Turn around time")
for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
print(" " + str(processes[i]) + "\t\t" + str(bt[i]) + "\t\t " + str(wt[i]) + "\t\t " + str(tat[i]))
print("\nAverage waiting time = " + str(total_wt / n))
print("Average turn around time = " + str(total_tat / n))
if __name__ == "__main__":
processes = [1, 2, 3]
n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time)
OUTPUT
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")
LINEAR SEARCH:
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
OUTPUT:
BINARY SEARCH
40 Found at index 3
LINEAR SEARCH
Element found at index 6
EX.NO:7B IMPLEMENTATION OF SORTING
CODING:
Quick Sort:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
insertionSort(arr)
print("The sorted array is:")
for i in range(len(arr)):
print(arr[i])
OUTPUT:
Quick Sorted array
is:
23455678
r
t
t
u
EX.NO:8 IMPLEMENTATION OF HASH TABLES
CODING:
OUTPUT
CODING:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data, end=" ")
if self.right:
self.right.PrintTree()
OUTPUT:
3 6 12 14
EX.NO:9B TREE TRAVERSAL ALGORITHMS
CODING:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val, end=" ")
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val, end=" ")
def printPreorder(root):
if root:
print(root.val, end=" ")
printPreorder(root.left)
printPreorder(root.right)
# Construct the binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Print traversals
print("Preorder traversal of binary tree is:")
printPreorder(root)
print("\nInorder traversal of binary tree is:")
printInorder(root)
print("\nPostorder traversal of binary tree is:")
printPostorder(root)
OUTPUT:
CODING:
import heapq
# Create a list
H = [21, 1, 45, 78, 3, 5]
# Convert the list into a heap
heapq.heapify(H)
print("Heap after heapify:", H)
# Push an element into the heap
heapq.heappush(H, 8)
print("Heap after push:", H)
OUTPUT:
CODING:
class Graph:
def __init__(self, gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
graph_elements = {
"a": ["b", "c"],
"b": ["a", "d"],
"c": ["a", "d"],
"d": ["e"],
"e": ["d"]
}
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):
edgeSet = []
for vertex in self.gdict:
for nextVertex in self.gdict[vertex]:
if {nextVertex, vertex} not in edgeSet:
edgeSet.append({vertex, nextVertex})
return edgeSet
graph_elements = {
"a": ["b", "c"],
"b": ["a", "d"],
"c": ["a", "d"],
"d": ["e"],
"e": ["d"]
}
g = Graph(graph_elements)
print(g.edges())
OUTPUT:
Displaying Vertices
['a', 'b', 'c', 'd', 'e']
Displaying Edges
[{'b', 'a'}, {'a', 'c'}, {'b', 'd'}, {'d', 'c'}, {'d', 'e'}]
EX.NO:12B GRAPH TRAVERSAL ALGORITHMS
CODING:
BFS:
import collections
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
print(str(vertex) + " ", end="")
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal:")
bfs(graph, 0)
OUTPUT:
Following is Breadth First Traversal:
0123
DFS:
import sys
def ret_graph():
return {
'A': {'B': 5.5, 'C': 2, 'D': 6},
'B': {'A': 5.5, 'E': 3},
'C': {'A': 2, 'F': 2.5},
'D': {'A': 6, 'F': 1.5},
'E': {'B': 3, 'J': 7},
'F': {'C': 2.5, 'D': 1.5, 'K': 1.5, 'G': 3.5},
'G': {'F': 3.5, 'I': 4},
'H': {'J': 2},
'I': {'G': 4, 'J': 4},
'J': {'H': 2, 'I': 4},
'K': {'F': 1.5}
}
start = 'A'
dest = 'J'
visited = []
stack = []
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr = stack.pop()
path.append(curr)
for neigh in graph[curr]:
if neigh not in visited:
visited.append(neigh)
stack.append(neigh)
if neigh == dest:
print("FOUND:", neigh)
print(path)
sys.exit(0)
print("Not found")
print(path)
OUTPUT:
FOUND: J
['A', 'D', 'F', 'K', 'G', 'I', 'J']
EX.NO:13 IMPLEMENTATION OF SINGLE SOURCE SHORTEST PATH
CODING:
OUTPUT
CODING:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def kruskal_algo(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = [i for i in range(self.V)]
rank = [0] * self.V
g.kruskal_algo()
OUTPUT:
1 - 2: 2
2 - 5: 2
3 - 2: 3
5 - 4: 3
0 - 1: 4
2 - 3: 3