Skip to content

Commit 4230ef2

Browse files
author
Abdelrahman Ahmed
committed
updated add_neighbor and add_edge method so that the graph is weighted
1 parent c289db1 commit 4230ef2

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

graph_adjacency-list.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ def __init__(self, n):
44
self.name = n
55
self.neighbors = list()
66

7-
def add_neighbor(self, v):
7+
def add_neighbor(self, v, weight):
88
if v not in self.neighbors:
9-
self.neighbors.append(v)
9+
self.neighbors.append((v, weight))
1010
self.neighbors.sort()
1111

1212
class Graph:
@@ -19,11 +19,11 @@ def add_vertex(self, vertex):
1919
else:
2020
return False
2121

22-
def add_edge(self, u, v):
22+
def add_edge(self, u, v, weight=0):
2323
if u in self.vertices and v in self.vertices:
2424
# 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)
25+
self.vertices[u].add_neighbor(v, weight)
26+
self.vertices[v].add_neighbor(u, weight)
2727
return True
2828
else:
2929
return False

0 commit comments

Comments
 (0)