Python Forum
Dijkstra code - trying to simplify it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dijkstra code - trying to simplify it
#1
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]:
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)] = distance
In[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 kpfad
In [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
Reply
#2
Please do not post new thread on same subject.
Forum rule: Do Not make A
Quote:new redundant thread on your same question. If someone has told you to include more information, edit your original post or create a new post in your thread. If you don't like the answer, talk about it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dijkstra algorithm helping find new space 1bumcheek 7 949 Jul-28-2023, 08:30 AM
Last Post: Gribouillis
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,130 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
Thumbs Up [SOLVED] Simplify condition test in if block? Winfried 2 1,715 Aug-25-2021, 09:42 PM
Last Post: Winfried
  How can i simplify this code Jezani_VIII 4 2,767 Aug-25-2019, 02:23 PM
Last Post: perfringo
  How to simplify square finding program? meknowsnothing 3 2,914 Jun-11-2019, 08:20 PM
Last Post: meknowsnothing
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,047 Jun-11-2019, 01:19 AM
Last Post: nholtz
  simplify my excel work on python CodeAyoub 1 2,938 Oct-08-2017, 12:09 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020