Files
ihk-dijkstra/dijsktra.py
2022-07-27 18:18:44 +02:00

65 lines
2.3 KiB
Python

"""
This module holds the logic for the solving
"""
class Dijkstra():
def __init__(self, graph: dict, connection: tuple):
"""
table: matrix with vertex as key, price and prev vertex as value
OL: open list, to keep track of finished vertecis
"""
self.graph = graph
self.table = {}
for vertex in graph:
self.table.update({vertex: {
"distance": (9999999, 999999),
"prev": None}})
self.table[connection[0]]["distance"] = (0, 0)
def algorithm(self, switch: str):
assert(switch == "time" or switch == "co2")
print("Performing Dijkstra on the following graph...")
for vertex in self.graph:
print(f"{vertex}: {self.graph[vertex]}")
print("")
for v1 in self.graph.keys():
neighbors = self.graph[v1]
for n in neighbors:
key = [elem for elem in n.keys()][0] # name of neighbor node
edge = (n[key]["time"], n[key]["co2"])
# update both time and co2
time = self.table[v1]["distance"][0] + edge[0]
co2 = self.table[v1]["distance"][1] + edge[1]
# but only eval the one we want
if switch == "time":
if time < self.table[key]["distance"][0]:
self.table[key]["distance"] = (time, co2)
self.table[key]["prev"] = v1
elif switch == "co2":
if co2 < self.table[key]["distance"][1]:
self.table[key]["distance"] = (time, co2)
self.table[key]["prev"] = v1
print("Final Dijkstra table:", self.table)
def print_result(self, connection: tuple):
sequence = []
(start, dest) = connection
# start at destination
sequence.append(dest)
# go through all possibilities until we're back at start
while start not in sequence:
current = self.table[sequence[-1]] # last element of list
prev = current["prev"]
sequence.append(prev)
sequence.reverse()
print(sequence)
print("Total Time:", self.table[dest]["distance"][0])
print("Total CO2:", self.table[dest]["distance"][1])