mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-08 23:05:54 +00:00
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
This commit is contained in:
parent
c57c4ca1a1
commit
28c02a1f21
@ -1,14 +1,17 @@
|
|||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
|
||||||
def printDist(dist, V):
|
def printDist(dist, V):
|
||||||
print("\nVertex Distance")
|
print("Vertex Distance")
|
||||||
for i in range(V):
|
distances = ("INF" if d == float("inf") else d for d in dist)
|
||||||
if dist[i] != float("inf"):
|
print("\t".join(f"{i}\t{d}" for i, d in enumerate(distances)))
|
||||||
print(i, "\t", int(dist[i]), end="\t")
|
|
||||||
else:
|
|
||||||
print(i, "\t", "INF", end="\t")
|
|
||||||
print()
|
|
||||||
|
|
||||||
|
|
||||||
def BellmanFord(graph, V, E, src):
|
def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int:
|
||||||
|
r"""
|
||||||
|
Returns shortest paths from a vertex src to all
|
||||||
|
other vertices.
|
||||||
|
"""
|
||||||
mdist = [float("inf") for i in range(V)]
|
mdist = [float("inf") for i in range(V)]
|
||||||
mdist[src] = 0.0
|
mdist[src] = 0.0
|
||||||
|
|
||||||
@ -30,6 +33,7 @@ def BellmanFord(graph, V, E, src):
|
|||||||
return
|
return
|
||||||
|
|
||||||
printDist(mdist, V)
|
printDist(mdist, V)
|
||||||
|
return src
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
@ -38,7 +42,7 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
graph = [dict() for j in range(E)]
|
graph = [dict() for j in range(E)]
|
||||||
|
|
||||||
for i in range(V):
|
for i in range(E):
|
||||||
graph[i][i] = 0.0
|
graph[i][i] = 0.0
|
||||||
|
|
||||||
for i in range(E):
|
for i in range(E):
|
||||||
|
Loading…
x
Reference in New Issue
Block a user