Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python dijkstra implementation stack

nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
distances = {
    'B': {'A': 5, 'D': 1, 'G': 2},
    'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5},
    'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3},
    'G': {'B': 2, 'D': 1, 'C': 2},
    'C': {'G': 2, 'E': 1, 'F': 16},
    'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2},
    'F': {'A': 5, 'E': 2, 'C': 16}}

unvisited = {node: None for node in nodes} #using None as +inf
visited = {}
current = 'B'
currentDistance = 0
unvisited[current] = currentDistance

while True:
    for neighbour, distance in distances[current].items():
        if neighbour not in unvisited: continue
        newDistance = currentDistance + distance
        if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
            unvisited[neighbour] = newDistance
    visited[current] = currentDistance
    del unvisited[current]
    if not unvisited: break
    candidates = [node for node in unvisited.items() if node[1]]
    current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]

print(visited)
Comment

PREVIOUS NEXT
Code Example
Python :: Mat.at(row,col) Opencv 
Python :: code runner runs python 2 
Python :: pythongalaxy.com 
Python :: python in a nutshell 
Python :: crear ondas segun musica python 
Python :: comment enleve les chiffre duplice d une liste python 
Python :: python excel zelle schreiben 
Python :: response object has no code 
Python :: python read stdin to string 
Python :: pandas condense dataframe by summing according to ID 
Python :: extends template django file system 
Python :: zen of python source code 
Python :: fibonacci series python program 
Python :: removing stop words in python 
Python :: python multiprocessing queu empty error 
Python :: Spansk dansk 
Python :: discord.py get user input (simplified) 
Python :: bs.newtag() inner html 
Python :: invalid literal for int() with base 10 python 
Python :: step out pdb python 
Python :: take substring of every element in dataframe 
Python :: how to catch chunkedencodingerror 
Python :: round(len(required_skills.intersection(resume_skills)) / len(required_skills) * 100, 0) 
Python :: how to run 2 async function forever 
Python :: pairplot hide original legend 
Python :: get ggplot colorpalette python 
Python :: print same index and value on each iteration of the for loop in Python 
Python :: Add OR Concatenation of Tuples in python 
Python :: df .isna percentage 
Python :: how to stop a function from returning none 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =