Skip to content

Commit e1327cd

Browse files
committed
Add doctest and fix mypy type annotation in bellman ford
1 parent daeb6a7 commit e1327cd

File tree

1 file changed

+36
-39
lines changed

1 file changed

+36
-39
lines changed

graphs/bellman_ford.py

Lines changed: 36 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,53 @@
1-
from __future__ import annotations
1+
from typing import Dict, List
22

33

4-
def printDist(dist, V):
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)))
4+
def print_distance(distance: List[float], src):
5+
print(f"Vertex\tShortest Distance from vertex {src}")
6+
for i, d in enumerate(distance):
7+
print(f"{i}\t\t{d}")
88

99

10-
def BellmanFord(graph: list[dict[str, int]], V: int, E: int, src: int) -> int:
10+
def bellman_ford(
11+
graph: List[Dict[str, int]], vertex_count: int, edge_count: int, src: int
12+
) -> List[float]:
1113
"""
1214
Returns shortest paths from a vertex src to all
1315
other vertices.
16+
>>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)]
17+
>>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges]
18+
>>> bellman_ford(g, 4, 4, 0)
19+
[0.0, -2.0, 8.0, 5.0]
20+
>>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges + [(1, 3, 5)]]
21+
>>> bellman_ford(g, 4, 5, 0)
22+
Traceback (most recent call last):
23+
...
24+
Exception: Negative cycle found
1425
"""
15-
mdist = [float("inf") for i in range(V)]
16-
mdist[src] = 0.0
26+
distance = [float("inf")] * vertex_count
27+
distance[src] = 0.0
1728

18-
for i in range(V - 1):
19-
for j in range(E):
20-
u = graph[j]["src"]
21-
v = graph[j]["dst"]
22-
w = graph[j]["weight"]
29+
for i in range(vertex_count - 1):
30+
for j in range(edge_count):
31+
u, v, w = graph[j]["src"], graph[j]["dst"], graph[j]["weight"]
2332

24-
if mdist[u] != float("inf") and mdist[u] + w < mdist[v]:
25-
mdist[v] = mdist[u] + w
26-
for j in range(E):
27-
u = graph[j]["src"]
28-
v = graph[j]["dst"]
29-
w = graph[j]["weight"]
33+
if distance[u] != float("inf") and distance[u] + w < distance[v]:
34+
distance[v] = distance[u] + w
3035

31-
if mdist[u] != float("inf") and mdist[u] + w < mdist[v]:
32-
print("Negative cycle found. Solution not possible.")
33-
return
36+
for j in range(edge_count):
37+
u, v, w = graph[j]["src"], graph[j]["dst"], graph[j]["weight"]
3438

35-
printDist(mdist, V)
36-
return src
39+
if distance[u] != float("inf") and distance[u] + w < distance[v]:
40+
raise Exception("Negative cycle found")
3741

42+
return distance
3843

39-
if __name__ == "__main__":
40-
V = int(input("Enter number of vertices: ").strip())
41-
E = int(input("Enter number of edges: ").strip())
42-
43-
graph = [dict() for j in range(E)]
4444

45-
for i in range(E):
46-
graph[i][i] = 0.0
45+
if __name__ == "__main__":
46+
edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)]
47+
g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges]
48+
shortest_distance = bellman_ford(g, 4, 4, 0)
49+
print_distance(shortest_distance, 0)
4750

48-
for i in range(E):
49-
print("\nEdge ", i + 1)
50-
src = int(input("Enter source:").strip())
51-
dst = int(input("Enter destination:").strip())
52-
weight = float(input("Enter weight:").strip())
53-
graph[i] = {"src": src, "dst": dst, "weight": weight}
51+
import doctest
5452

55-
gsrc = int(input("\nEnter shortest path source:").strip())
56-
BellmanFord(graph, V, E, gsrc)
53+
doctest.testmod()

0 commit comments

Comments
 (0)