class Graph:
def __init__(self):
self.adj_list = {}
# Print the graph
def print_graph(self):
for vertex in self.adj_list:
print(vertex, ':', self.adj_list[vertex])
# Add a vertex to the graph
def add_vertex(self, vertex):
if vertex not in self.adj_list.keys():
self.adj_list[vertex] = []
return True
return False
# Add an edge between two vertices
def add_edge(self, v1, v2):
if v1 in self.adj_list.keys() and v2 in self.adj_list.keys():
self.adj_list[v1].append(v2)
self.adj_list[v2].append(v1)
return True
return False
# Remove an edge between two vertices
def remove_edge(self, v1, v2):
if v1 in self.adj_list.keys() and v2 in self.adj_list.keys():
try:
self.adj_list[v1].remove(v2)
self.adj_list[v2].remove(v1)
except ValueError:
pass
return True
return False
# Remove a vertex from the graph
def remove_vertex(self, vertex):
if vertex in self.adj_list.keys():
for other_vertex in self.adj_list[vertex]:
self.adj_list[other_vertex].remove(vertex)
del self.adj_list[vertex]
return True
return False