Skip to content

Commit 0d5c25c

Browse files
committed
Add doctests to dijkstra_2.py
1 parent 5f66061 commit 0d5c25c

File tree

1 file changed

+63
-2
lines changed

1 file changed

+63
-2
lines changed

graphs/dijkstra_2.py

+63-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,47 @@
11
def print_dist(dist, v):
2+
"""
3+
Print vertex distance
4+
5+
Examples:
6+
>>> print_dist([float('inf'),float('inf'),float('inf')], 3)
7+
<BLANKLINE>
8+
Vertex Distance
9+
0 INF
10+
1 INF
11+
2 INF
12+
>>> print_dist([2.0,6.0,10.0,3.0], 4)
13+
<BLANKLINE>
14+
Vertex Distance
15+
0 2
16+
1 6
17+
2 10
18+
3 3
19+
>>> print_dist([], 4)
20+
Traceback (most recent call last):
21+
...
22+
IndexError: list index out of range
23+
"""
224
print("\nVertex Distance")
325
for i in range(v):
426
if dist[i] != float("inf"):
5-
print(i, "\t", int(dist[i]), end="\t")
27+
print(i, " ", int(dist[i]), end="")
628
else:
7-
print(i, "\t", "INF", end="\t")
29+
print(i, " ", "INF", end="")
830
print()
931

1032

1133
def min_dist(mdist, vset, v):
34+
"""
35+
Finds the index of the node with the minimum distance between no-visited nodes
36+
37+
Examples:
38+
>>> dist = [0.0, float('inf'), float('inf'), float('inf')]
39+
>>> set = [False, False, False, False]
40+
>>> min_dist(dist, set, 4)
41+
0
42+
>>> min_dist([], [], 0)
43+
-1
44+
"""
1245
min_val = float("inf")
1346
min_ind = -1
1447
for i in range(v):
@@ -19,6 +52,30 @@ def min_dist(mdist, vset, v):
1952

2053

2154
def dijkstra(graph, v, src):
55+
"""
56+
Dijkstra's algorithm to calculate the shortest distances from the src source node
57+
to all other nodes in a graph represented as an adjacency matrix.
58+
59+
Examples:
60+
>>> G1 = [[0.0, 6.0, 2.0, float('inf')],
61+
... [float('inf'), 0.0, 9.0, 1.0],
62+
... [float('inf'), float('inf'), 0.0, 3.0],
63+
... [float('inf'), float('inf'), float('inf'), 0.0]]
64+
>>> dijkstra(G1, 4, 5)
65+
Traceback (most recent call last):
66+
...
67+
IndexError: list assignment index out of range
68+
>>> G2 = [[0.0, 6.0, 2.0, float('inf')],
69+
... [float('inf'), 0.0, 9.0, 1.0],
70+
... [float('inf'), float('inf'), 0.0, 3.0],
71+
... [float('inf'), float('inf'), float('inf'), 0.0]]
72+
>>> dijkstra(G2, 4, 0)
73+
<BLANKLINE>
74+
Vertex Distance
75+
0 0
76+
1 6
77+
2 2
78+
"""
2279
mdist = [float("inf") for _ in range(v)]
2380
vset = [False for _ in range(v)]
2481
mdist[src] = 0.0
@@ -39,6 +96,10 @@ def dijkstra(graph, v, src):
3996

4097

4198
if __name__ == "__main__":
99+
import doctest
100+
101+
doctest.testmod(verbose=True)
102+
42103
V = int(input("Enter number of vertices: ").strip())
43104
E = int(input("Enter number of edges: ").strip())
44105

0 commit comments

Comments
 (0)