Skip to content

feat: Implement add_vertex and remove_vertex for AdjacencyMatrix #640

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions pydatastructs/graphs/adjacency_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,30 @@ def neighbors(self, node):
return neighbors

def add_vertex(self, node):
raise NotImplementedError("Currently we allow "
"adjacency matrix for static graphs only")
node_name = str(node.name)
if node_name in self.vertices:
raise ValueError(f"Vertex {node_name} already exists in the graph.")
self.vertices.append(node_name)
self.__setattr__(node_name, node)
self.matrix[node_name] = {}
for vertex in self.vertices:
self.matrix[vertex][node_name] = False
self.matrix[node_name][vertex] = False

def remove_vertex(self, node):
raise NotImplementedError("Currently we allow "
"adjacency matrix for static graphs only.")
node_name = str(node)
if node_name not in self.vertices:
raise ValueError(f"Vertex {node_name} does not exist in the graph.")
self.vertices.remove(node_name)
del self.matrix[node_name]
for vertex in self.vertices:
del self.matrix[vertex][node_name]
edges_to_remove = []
for edge in self.edge_weights.keys():
if node_name in edge:
edges_to_remove.append(edge)
for edge in edges_to_remove:
del self.edge_weights[edge]

def add_edge(self, source, target, cost=None):
source, target = str(source), str(target)
Expand Down
9 changes: 9 additions & 0 deletions pydatastructs/graphs/tests/test_adjacency_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,12 @@ def test_AdjacencyMatrix():
assert raises(ValueError, lambda: g.add_edge('v', 'x'))
assert raises(ValueError, lambda: g.add_edge(2, 3))
assert raises(ValueError, lambda: g.add_edge(3, 2))
v_3 = AdjacencyMatrixGraphNode(3, 3)
g.add_vertex(v_3)
assert '3' in g.vertices
assert g.is_adjacent(3, 0) is False
g.add_edge(3, 0, 0)
assert g.is_adjacent(3, 0) is True
g.remove_vertex(3)
assert '3' not in g.vertices
assert raises(ValueError, lambda: g.add_edge(3, 0))
Loading