Skip to content

Commit 738e2f5

Browse files
committedApr 7, 2021
Separate the data from the logic (chap07 graph)
1 parent f6e7625 commit 738e2f5

File tree

3 files changed

+15
-27
lines changed

3 files changed

+15
-27
lines changed
 

‎chap07_graphs/data.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
edges_with_weights = (
2+
("a", "b", 7),
3+
("a", "c", 9),
4+
("a", "f", 14),
5+
("b", "c", 10),
6+
("b", "d", 15),
7+
("c", "d", 11),
8+
("c", "f", 2),
9+
("d", "e", 6),
10+
("e", "f", 9),
11+
)

‎chap07_graphs/dijkstra.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Ref: https://dev.to/mxl/dijkstras-algorithm-in-python-algorithms-for-beginners-dkc
2+
from data import edges_with_weights as edges
23

34
from collections import deque, namedtuple
45
from math import inf
@@ -25,8 +26,7 @@ def __init__(self, edges):
2526

2627
@property
2728
def vertices(self):
28-
"""Return a set of strings that stands for vertices/nodes.
29-
"""
29+
"""Return a set of strings that stands for vertices/nodes."""
3030
return set(sum(([edge.start, edge.end] for edge in self.edges), []))
3131

3232
@property
@@ -137,19 +137,7 @@ def remove_edge(self, node1, node2, both_ends=True):
137137

138138

139139
def main() -> None:
140-
graph = Graph(
141-
[
142-
("a", "b", 7),
143-
("a", "c", 9),
144-
("a", "f", 14),
145-
("b", "c", 10),
146-
("b", "d", 15),
147-
("c", "d", 11),
148-
("c", "f", 2),
149-
("d", "e", 6),
150-
("e", "f", 9),
151-
]
152-
)
140+
graph = Graph(edges)
153141

154142
assert graph.dijkstra("a", "e") == deque(["a", "c", "d", "e"])
155143

‎chap07_graphs/plot_weighted_graph.py

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,14 @@
11
# References:
22
# https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_weighted_graph.html
33
# https://stackoverflow.com/questions/56597840/drawing-weighted-graph-from-adjacency-matrix-with-edge-labels
4+
from data import edges_with_weights as edges
45

56
import matplotlib.pyplot as plt
67
import networkx as nx
78

89
# Graph = nx.Graph()
910
Graph = nx.DiGraph(directed=True)
1011

11-
edges = (
12-
("a", "b", 7),
13-
("a", "c", 9),
14-
("a", "f", 14),
15-
("b", "c", 10),
16-
("b", "d", 15),
17-
("c", "d", 11),
18-
("c", "f", 2),
19-
("d", "e", 6),
20-
("e", "f", 9),
21-
)
22-
2312
for orig, dest, weight in edges:
2413
Graph.add_edge(orig, dest, weight=weight)
2514

0 commit comments

Comments
 (0)