Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

class Graph:

def __init__(self):
self.vertices = {}

def add_vertex(self, vertex):


if vertex not in self.vertices:
self.vertices[vertex] = {}

def add_edge(self, start, end, weight):


if start in self.vertices and end in self.vertices:
self.vertices[start][end] = weight
# Uncomment below line for undirected graph
# self.vertices[end][start] = weight

def remove_vertex(self, vertex):


if vertex in self.vertices:
del self.vertices[vertex]
for v in self.vertices:
if vertex in self.vertices[v]:
del self.vertices[v][vertex]

def remove_edge(self, start, end):


if start in self.vertices and end in self.vertices:
if end in self.vertices[start]:
del self.vertices[start][end]
# Uncomment below line for undirected graph
# del self.vertices[end][start]

def get_vertices(self):
return list(self.vertices.keys())

def get_edges(self):
edges = []
for start, connections in self.vertices.items():
for end, weight in connections.items():
edges.append((start, end, weight))
return edges

def display_graph(self):
print("Graph:")
for start, connections in self.vertices.items():
for end, weight in connections.items():
print(f"{start} - {weight} -> {end}")
print()

# Example Usage:
graph = Graph()
vertices = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
for vertex in vertices:
graph.add_vertex(vertex)

graph.add_edge("A", "B", 2)
graph.add_edge("A", "C", 4)
graph.add_edge("B", "C", 1)
graph.add_edge("B", "D", 3)
graph.add_edge("C", "E", 5)
graph.add_edge("D", "F", 2)
graph.add_edge("E", "G", 4)
graph.add_edge("F", "H", 3)
graph.add_edge("G", "I", 2)
graph.add_edge("H", "J", 4)
graph.add_edge("I", "K", 1)
:
graph.add_edge("J", "L", 2)

# Display the graph


graph.display_graph()
:

You might also like