change a bit the function

This commit is contained in:
2025-05-28 08:12:58 +02:00
parent 9e0982257c
commit 45054aef03

View File

@@ -1,28 +1,44 @@
def bellman_ford(graphe, sommet): def bellman(graphe, sommet):
"""Une fonction qui prend en parametre un graphe et renvoie un dictionnaire contenant le cout des chemins de tous les points du graphe
Args:
graphe (dict): dictionnaire
sommet (str): le point de depart
Raises:
ValueError: boucle infini (quand la comme des cout est negative)
Returns:
dict: un dictionnaire contenant les couts
>>> bellman({"A":[("B",3),("C",4)],"B":[("C",0)],"C":[]},"A")
{'A': 0, 'B': 3, 'C': 3}
"""
distance = {sommet: float("inf") for sommet in graphe} distance = {sommet: float("inf") for sommet in graphe}
distance[sommet] = 0 distance[sommet] = 0
for i in range(len(graphe) - 1): for i in range(len(graphe) - 1):
for u in graphe: for j in graphe:
for v, coef in graphe[u]: for k, coef in graphe[j]:
if distance[u] + coef < distance[v]: if distance[j] + coef < distance[k]:
distance[v] = distance[u] + coef distance[k] = distance[j] + coef
for u in graphe: for j in graphe:
for v, coef in graphe[u]: for k, coef in graphe[j]:
if distance[u] + coef < distance[v]: if distance[j] + coef < distance[k]:
raise ValueError("Cycle négatif détecté") raise ValueError("Cycle infini (le valeurs deviennent de plus en plus petite vers -inf)")
return distance return distance
if __name__ == "__main__": if __name__ == "__main__":
import doctest
doctest.testmod()
graphe = { graphe = {
"A": [("G", 8), ("H", 4)], "A": [("G", 8), ("H", 4)],
"G": [("H", 1), ("L", 2)], "G": [("H", 1), ("L", 2)],
"H": [("L", 5), ("E", 7)], "H": [("L", 5), ("E", 7)],
"L": [("E", -2)], "L": [("E", 2)],
"E": [], "E": [],
} }
distances = bellman_ford(graphe, "A") distances = bellman(graphe, "A")
print(distances) print(distances)