Skip to content

Commit 802830f

Browse files
committed
fixed add_edge function, much faster without using for loop
1 parent 4c3aea8 commit 802830f

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

graph_adjacency-list.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# implementation of an undirected graph using Adjacency Lists
12
class Vertex:
23
def __init__(self, n):
34
self.name = n
@@ -20,11 +21,9 @@ def add_vertex(self, vertex):
2021

2122
def add_edge(self, u, v):
2223
if u in self.vertices and v in self.vertices:
23-
for key, value in self.vertices.items():
24-
if key == u:
25-
value.add_neighbor(v)
26-
if key == v:
27-
value.add_neighbor(u)
24+
# my YouTube video shows a silly for loop here, but this is a much faster way to do it
25+
self.vertices[u].add_neighbor(v)
26+
self.vertices[v].add_neighbor(u)
2827
return True
2928
else:
3029
return False

0 commit comments

Comments
 (0)