MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / remove_vertex

Method remove_vertex

graphs/graph_adjacency_list.py:107–130  ·  view source on GitHub ↗

Removes the given vertex from the graph and deletes all incoming and outgoing edges from the given vertex as well. If the given vertex does not exist, a ValueError will be thrown.

(self, vertex: T)

Source from the content-addressed store, hash-verified

105 self.adj_list[destination_vertex].append(source_vertex)
106
107 def remove_vertex(self, vertex: T) -> None:
108 """
109 Removes the given vertex from the graph and deletes all incoming and
110 outgoing edges from the given vertex as well. If the given vertex
111 does not exist, a ValueError will be thrown.
112 """
113 if not self.contains_vertex(vertex):
114 msg = f"Incorrect input: {vertex} does not exist in this graph."
115 raise ValueError(msg)
116
117 if not self.directed:
118 # If not directed, find all neighboring vertices and delete all references
119 # of edges connecting to the given vertex
120 for neighbor in self.adj_list[vertex]:
121 self.adj_list[neighbor].remove(vertex)
122 else:
123 # If directed, search all neighbors of all vertices and delete all
124 # references of edges connecting to the given vertex
125 for edge_list in self.adj_list.values():
126 if vertex in edge_list:
127 edge_list.remove(vertex)
128
129 # Finally, delete the given vertex and all of its outgoing edge references
130 self.adj_list.pop(vertex)
131
132 def remove_edge(self, source_vertex: T, destination_vertex: T) -> None:
133 """

Calls 3

contains_vertexMethod · 0.95
removeMethod · 0.45
popMethod · 0.45