This community-built FAQ covers the “Dijkstra’s Algorithm in Python: Review” exercise from the lesson “Dijkstra’s Algorithm: Python”.
Paths and Courses
This exercise can be found in the following Codecademy content:
Computer Science
FAQs on the exercise Dijkstra’s Algorithm in Python: Review
There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (
) below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply (
) below!
Agree with a comment or answer? Like (
) to up-vote the contribution!
Need broader help or resources? Head here.
Looking for motivation to keep learning? Join our wider discussions.
Learn more about how to use this guide.
Found a bug? Report it!
Have a question about your account or billing? Reach out to our customer support team!
None of the above? Find out where to ask other questions here!
In the instruction video, there is an “unvisited” list containing all the unvisited vertices, and it contains every vertex at first. In each iteration, the smallest one will be popped out using a min heap. However, in the python implementation, this list, vertices_to_explore, does not contain all vertices at first; it only has the start vertex at first, and other vertices are added to the list during the iteration. What are the differences?
1 Like
In the code implementation we are storing two values: the vertex itself and its relative cost
ex (“A”, 0) in the video explanation the list only contains a visual reference of the “unvisited” vertices
The practical implementation is correct because we are not just popping off the cheapest vertices but we are updating and pushing back with the updated cost.
By the way in the code I see that the unvisited_vertex variable is initialized: [(0, start)] wich could stay the same as they are in the relative graph: [(start, 0)] wich will cause less confusion in the code implementation.
def dijkstra(graph, start):
distances = {}
for vertex in graph:
distances[vertex] = inf
distances[start] = 0
unvisited_vertex = [(start, 0)]
while unvisited_vertex:
current_vertex, distance = heappop(unvisited_vertex)
for neighbor, weight in graph[current_vertex]:
new_distance = distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heappush(unvisited_vertex, (neighbor, new_distance))
return distances