0% found this document useful (0 votes)
2 views

AD3271 Coding and Output

The document outlines various implementations of data structures and algorithms in Python, including stacks, queues, linked lists, and searching/sorting algorithms. It provides code examples for each data structure and algorithm, demonstrating their functionality and output. Additionally, it covers applications of these structures, such as polynomial addition and expression conversion.

Uploaded by

germeni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

AD3271 Coding and Output

The document outlines various implementations of data structures and algorithms in Python, including stacks, queues, linked lists, and searching/sorting algorithms. It provides code examples for each data structure and algorithm, demonstrating their functionality and output. Additionally, it covers applications of these structures, such as polynomial addition and expression conversion.

Uploaded by

germeni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

EX.

NO:1 IMPLEMENT SIMPLE ADTs AS PYTHON CLASSES

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

Stack after elements are popped:


[]

Queue:
Initial queue:

['a', 'b', 'c']

Elements dequeued from queue:


a
b
c
Queue after removing elements:
[]
List:
Initial List:

[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 :

# Part 1: Extend operation on a list


List = [1, 2, 3, 4]
print("Initial List:")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation:")
print(List)
# Part 2: Creating and printing blank and other lists
List = []
print("\nBlank 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])
# Part 3: Insert operation on a list
List = [1, 2, 3, 4]
print("\nInitial List:")
print(List)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation:")
print(List)
# Part 4: Remove operation on a list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("\nInitial List:")
print(List)
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements:")
print(List)
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements:")
print(List)
# Part 5: Multi-dimensional list
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List:")
print(List)
OUTPUT:
Initial List:
[1, 2, 3, 4]

List after performing Extend Operation:


[1, 2, 3, 4, 8, 'Geeks', 'Always']

Blank List:
[]

List of numbers:
[10, 20, 14]

List Items:
Geeks
Geeks

Initial List:
[1, 2, 3, 4]

List after performing Insert Operation:


['Geeks', 1, 2, 3, 12, 4]

Initial 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]

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
EX.NO:5 IMPLEMENTATION OF STACK AND QUEUE ADTs

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)
OUTPUT:

Stack:
Initial stack:
['a', 'b', 'c']

Elements popped from stack:


c
b
a

Stack after elements are popped:


[]

Queue:
Initial queue:

['a', 'b', 'c']

Elements dequeued from queue:

Queue after removing elements:

[]
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)

print("First polynomial is:")


printPoly(A, m)
print("Second polynomial is:")
printPoly(B, n)
sum_poly = add(A, B, m, n)
size = max(m, n)
print("Sum polynomial is:")
printPoly(sum_poly, size)

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)

while not self.isEmpty():


self.output.append(self.pop())
print("".join(self.output))
# Example usage
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)

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

Processes Burst time Waiting time Turn around time


1 10 0 10
2 5 10 15
3 8 15 23

Average waiting time = 8.333333333333334


Average turn around time = 16.0

EX.NO:7A IMPLEMENTATION OF SEARCHING ALGORITHMS


CODING:

def BinarySearch(arr, low, high, key):


if high >= low:
mid = (high + low) // 2
if arr[mid] == key:
return mid
elif arr[mid] > key:
return BinarySearch(arr, low, mid - 1, key)
else:
return BinarySearch(arr, mid + 1, high, key)
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")

LINEAR SEARCH:
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1

arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']


x = 'a'
result = linearsearch(arr, x)
if result != -1:
print("Element found at index", result)
else:
print("Element not found")

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 partition(arr, low, high):


i = (low - 1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return (i + 1)

def quickSort(arr, low, high):


if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi - 1)
quickSort(arr, pi + 1, high)
arr = [2, 5, 3, 8, 6, 5, 4, 7]
n = len(arr)
quickSort(arr, 0, n - 1)
print("Sorted array is:")
for i in range(n):
print(arr[i], end=" ")

Coding of Insertion 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

Insertion sorted array


is: a
i
l
o

r
t
t
u
EX.NO:8 IMPLEMENTATION OF HASH TABLES

CODING:

# Initialize hash table as a list of 10 empty lists


hashTable = [[] for _ in range(10)]

# Function to check if a number is prime


def checkPrime(n):
if n == 1 or n == 0:
return 0
for i in range(2, n//2):
if n % i == 0:
return 0
return 1

# Function to get the next prime number


def getPrime(n):
if n % 2 == 0:
n=n+1
while not checkPrime(n):
n += 2
return n

# Hash function to calculate the index


def hashFunction(key):
capacity = getPrime(10)
return key % capacity

# Function to insert data into the hash table


def insertData(key, data):
index = hashFunction(key)
hashTable[index].append((key, data))

# Function to remove data from the hash table


def removeData(key):
index = hashFunction(key)
# Removing the key-value pair from the list
for i, (k, _) in enumerate(hashTable[index]):
if k == key:
del hashTable[index][i]
break

# Inserting data into the hash table


insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")

print("Hash Table after insertion:")


print(hashTable)

# Removing data from the hash table


removeData(123)

print("Hash Table after removing key 123:")


print(hashTable)

OUTPUT

Hash Table after insertion:


[[(123, 'apple')], [], [(213, 'banana')], [(432, 'mango')], [(654, 'guava')], [], [], [], [], []]
Hash Table after removing key 123:
[[], [], [(213, 'banana')], [(432, 'mango')], [(654, 'guava')], [], [], [], [], []]
EX.NO:9A TREE REPRESENTATION

CODING:

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def insert(self, data):


if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data

def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data, end=" ")
if self.right:
self.right.PrintTree()

# Create a BST instance


root = Node(12)
# Insert elements into the BST
root.insert(6)
root.insert(14)
root.insert(3)

# Print the elements of the BST in sorted order


root.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:

Preorder traversal of binary tree is:


12453
Inorder traversal of binary tree is:
42513
Postorder traversal of binary tree is:
45231
Ex.No:10 IMPLEMENTATION OF BINARY SEARCH
CODING:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def findval(self, lkpval):
if lkpval < self.data:
if self.left is None:
return str(lkpval) + " Not Found"
return self.left.findval(lkpval)
elif lkpval > self.data:
if self.right is None:
return str(lkpval) + " Not Found"
return self.right.findval(lkpval)
else:
return str(self.data) + ' is found'
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data, end=" ")
if self.right:
self.right.PrintTree()
# Create a BST instance
root = Node(12)
# Insert elements into the BST
root.insert(6)
root.insert(14)
root.insert(3)
# Print the result of finding the value 7 in the BST
print(root.findval(7))
OUTPUT:
7 Not Found
EX.NO:11 IMPLEMENTATION OF HEAPS

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)

# Pop the smallest element from the heap


smallest = heapq.heappop(H)
print("Smallest element popped from heap:", smallest)
print("Heap after pop:", H)

OUTPUT:

Heap after heapify: [1, 3, 5, 78, 21, 45]


Heap after push: [1, 3, 5, 78, 21, 45, 8]
Smallest element popped from heap: 1
Heap after pop: [3, 8, 5, 78, 21, 45]
EX.NO:12A GRAPH REPRESENTATION

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:

from sys import maxsize


def BellmanFord(graph, V, E, src):
# Initialize distances array
dis = [maxsize] * V
dis[src] = 0
# Relax edges V-1 times
for i in range(V - 1):
for j in range(E):
u, v, weight = graph[j]
if dis[u] != maxsize and dis[u] + weight < dis[v]:
dis[v] = dis[u] + weight
# Check for negative weight cycles
for i in range(E):
u, v, weight = graph[i]
if dis[u] != maxsize and dis[u] + weight < dis[v]:
print("Graph contains negative weight cycle")
return
# Print distances from source
print("Vertex Distance from Source")
for i in range(V):
print("%d\t\t%d" % (i, dis[i]))
if __name__ == "__main__":
V = 5 # Number of vertices in graph
E = 8 # Number of edges in graph
graph = [
[0, 1, -1], [0, 2, 4], [1, 2, 3],
[1, 3, 2], [1, 4, 2], [3, 2, 5],
[3, 1, 1], [4, 3, -3]
]
BellmanFord(graph, V, E, 0)

OUTPUT

Vertex Distance from Source


0 0
1 -1
2 2
3 -2
4 1
EX.NO:14 IMPLEMENTATION OF MINIMUM SPANNING TREE ALGORITHMS

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 apply_union(self, parent, rank, x, y):


xroot = self.find(parent, x)
yroot = self.find(parent, y)

if rank[xroot] < rank[yroot]:


parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

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

while e < self.V - 1 and i < len(self.graph):


u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e += 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)

for u, v, weight in result:


print("%d - %d: %d" % (u, v, weight))
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)

g.kruskal_algo()

OUTPUT:

1 - 2: 2
2 - 5: 2
3 - 2: 3
5 - 4: 3
0 - 1: 4
2 - 3: 3

You might also like