1
1
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
+ """
2
24
print ("\n Vertex Distance" )
3
25
for i in range (v ):
4
26
if dist [i ] != float ("inf" ):
5
- print (i , "\t " , int (dist [i ]), end = "\t " )
27
+ print (i , " " , int (dist [i ]), end = "" )
6
28
else :
7
- print (i , "\t " , "INF" , end = "\t " )
29
+ print (i , " " , "INF" , end = "" )
8
30
print ()
9
31
10
32
11
33
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
+ """
12
45
min_val = float ("inf" )
13
46
min_ind = - 1
14
47
for i in range (v ):
@@ -19,6 +52,30 @@ def min_dist(mdist, vset, v):
19
52
20
53
21
54
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
+ """
22
79
mdist = [float ("inf" ) for _ in range (v )]
23
80
vset = [False for _ in range (v )]
24
81
mdist [src ] = 0.0
@@ -39,6 +96,10 @@ def dijkstra(graph, v, src):
39
96
40
97
41
98
if __name__ == "__main__" :
99
+ import doctest
100
+
101
+ doctest .testmod (verbose = True )
102
+
42
103
V = int (input ("Enter number of vertices: " ).strip ())
43
104
E = int (input ("Enter number of edges: " ).strip ())
44
105
0 commit comments