0% found this document useful (0 votes)
24 views2 pages

DSA Assignment About Graphs

This document defines classes and methods for representing and finding the minimum spanning tree of a weighted graph. It reads edge weights from a file, constructs the graph, and finds the minimum spanning tree using Prim's algorithm.

Uploaded by

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

DSA Assignment About Graphs

This document defines classes and methods for representing and finding the minimum spanning tree of a weighted graph. It reads edge weights from a file, constructs the graph, and finds the minimum spanning tree using Prim's algorithm.

Uploaded by

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

import heapq

class WeightedEdge:
def __init__(self, u, v, weight):
self.u = u
self.v = v
self.weight = weight
def __lt__(self, other_edge):
return self.weight < other_edge.weight
class Heap:
def __init__(self):
self.data = []
def push(self, item):
heapq.heappush(self.data, item)
def pop(self):
return heapq.heappop(self.data)
def size(self):
return len(self.data)
def peek(self):
return self.data[0]
def copy(heap_obj):
copied = []
for i in range(len(heap_obj)):
copied.append(Heap())
for e in heap_obj[i].data:
copied[i].push(e)
return copied
class WeightedGraph:
def __init__(self, lst_edges, num_vertices):
self.num_vertices = num_vertices
self.queues = self.helper(lst_edges)
def helper(self, list_of_edges):
lst = []
for i in range(self.num_vertices):
lst.append(Heap())
for i in range(len(list_of_edges)):
lst[list_of_edges[i].u].push(list_of_edges[i])
return lst
def printWeightedEdges(self):
print(f"The number of vertices is: {self.num_vertices}")
for i in range(len(self.queues)):
print(f"Vertex {str(i)}", end = ': ')
for edge in self.queues[i].data:
print(f"({str(edge.u)},{str(edge.v)},{str(edge.weight)} )", end = '
')
print()
def getMinimumSpanningTree(self, start=0):
Tree = [start]
parent = self.num_vertices * [-1]
t_weight = 0
queues = copy(self.queues)
while len(Tree) < self.num_vertices:
v = -1
least_weight = float("inf")
for u in Tree:
while queues[u].size() != 0 and queues[u].peek().v in Tree:
queues[u].pop()
if queues[u].size() == 0:
continue
edge = queues[u].peek()
if edge.weight < least_weight:
v = edge.v
least_weight = edge.weight
parent[v] = u
if v != -1:
Tree.append(v)
else:
break
t_weight += least_weight
return WeightedGraph_MST(start, parent, t_weight)
class WeightedGraph_MST:
def __init__(self, root, parent, total_weight):
self.root = root
self.parent = parent
self.total_weight = total_weight
def getTotalWeight(self):
print(f"Total weight is {self.total_weight}")
def printTree(self):
print("Root is: " + str(self.root))
print("Edges: ", end="")
for i in range(len(self.parent)):
if self.parent[i] != -1:
print(f"({str(self.parent[i])}, {str(i)}", end=") ")
file_name = input("Enter a file name: ")
with open(file_name, 'r') as f:
num_vertices = int(f.readline())
next_lines = f.readlines()
lst_edges = []
for i in range(len(next_lines)):
line = next_lines[i].split("|")
for j in range(len(line)):
edge = line[j].split(",")
lst_edges.append(WeightedEdge(int(edge[0]), int(edge[1]),
int(edge[2])))
lst_edges.append(WeightedEdge(int(edge[1]), int(edge[0]),
int(edge[2])))
g = WeightedGraph(lst_edges, num_vertices)
g.printWeightedEdges()
tree = g.getMinimumSpanningTree()
tree.getTotalWeight()
tree.printTree()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy