Jan-23-2019, 12:04 PM
(This post was last modified: Jan-23-2019, 12:04 PM by grandpapa10.)
Hello again peeps,
After hours struggling with my other code, I decided to start from scratch again.
I finally came up with a code that finds the shortest path in a graph.
Yet, I'm still not satisfied with it since it's too verbose and lacks the original intent. That is, the intent of implementing
the Dijkstra Algorithm in the most simple way as possible.
I'd love to get some suggestions !
In [1]:
Thanks a lot in advance
After hours struggling with my other code, I decided to start from scratch again.
I finally came up with a code that finds the shortest path in a graph.
Yet, I'm still not satisfied with it since it's too verbose and lacks the original intent. That is, the intent of implementing
the Dijkstra Algorithm in the most simple way as possible.
I'd love to get some suggestions !
In [1]:
from collections import defaultdict #edges = paths from_node = start_n to_node = end_n weight = distance class Graph(): def __init__(self): self.paths = defaultdict(list) self.distance = {} def path_maker(self, start_n, end_n, distance): self.paths[start_n].append(end_n) self.paths[end_n].append(start_n) self.distance[(start_n, end_n)] = distance self.distance[(end_n, start_n)] = distanceIn[2]:
graph = Graph()In[3]:
paths = [ ("WilliamWatt", "Volgershall", 1.1), ("WilliamWatt", "LeuphanaCampus", 3.9), ("WilliamWatt", "AmSande", 3.2), ("Volgershall", "AmSande", 2.8), ("Volgershall", "CityHall", 2), ("AmSande", "LeuphanaCampus", 2.6), ("AmSande", "CityHall", 2.5), ("AmSande", "TrainStation", 1.7), ("AmSande", "RotesFeld", 0.9), ("RotesFeld", "LeuphanaCampus", 1.7), ("RotesFeld", "TrainStation", 2.1), ("TrainStation", "CityHall", 2.6) ] for edge in edges: graph.add_edge(*edge)In[4]:
def pathfinder(graph, start, end): shortcut = {start: (None, 0)} location = start passed_by = set() while location != end: passed_by.add(location) pathways = graph.edges[location] distance_location = shortcut[location][1] for neighbor in pathways: distance = graph.weights[(location, neighbor)] + distance_location if neighbor not in shortcut: shortcut[neighbor] = (location, distance) else: actual_distance = shortcut[neighbor][1] if actual_distance > distance: shortcut[neighbor] = (location, distance) following_nodes = {x: shortcut[x] for x in shortcut if x not in passed_by} location = min(following_nodes, key=lambda y: following_nodes[y][1]) # Work back through destinations in shortest path kpfad = [] while location is not None: kpfad.append(location) neighbor = shortcut[location][0] location = neighbor # Reverse path kpfad = kpfad[::-1] return kpfadIn [5]:
pathfinder(graph, 'TrainStation', 'WilliamWatt')Output :
['TrainStation', 'AmSande', 'WilliamWatt']By the way, Im using Python 3 and Im running the code in the Jupyter Notebook!
Thanks a lot in advance