Skip to content

Commit 28c02a1

Browse files
authored
Improve bellman_ford.py (#1575)
* Fix out of range error in bellman_ford.py * Update bellman_ford.py * fixup! Format Python code with psf/black push * Enhance the print function * fixup! Format Python code with psf/black push
1 parent c57c4ca commit 28c02a1

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

graphs/bellman_ford.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
1+
from typing import Dict, List
2+
3+
14
def printDist(dist, V):
2-
print("\nVertex Distance")
3-
for i in range(V):
4-
if dist[i] != float("inf"):
5-
print(i, "\t", int(dist[i]), end="\t")
6-
else:
7-
print(i, "\t", "INF", end="\t")
8-
print()
5+
print("Vertex Distance")
6+
distances = ("INF" if d == float("inf") else d for d in dist)
7+
print("\t".join(f"{i}\t{d}" for i, d in enumerate(distances)))
98

109

11-
def BellmanFord(graph, V, E, src):
10+
def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int:
11+
r"""
12+
Returns shortest paths from a vertex src to all
13+
other vertices.
14+
"""
1215
mdist = [float("inf") for i in range(V)]
1316
mdist[src] = 0.0
1417

@@ -30,6 +33,7 @@ def BellmanFord(graph, V, E, src):
3033
return
3134

3235
printDist(mdist, V)
36+
return src
3337

3438

3539
if __name__ == "__main__":
@@ -38,7 +42,7 @@ def BellmanFord(graph, V, E, src):
3842

3943
graph = [dict() for j in range(E)]
4044

41-
for i in range(V):
45+
for i in range(E):
4246
graph[i][i] = 0.0
4347

4448
for i in range(E):

0 commit comments

Comments
 (0)