Output
There are multiple ways you can print out the path in the end, and it depends on how you
plan to store the path once it has been evaluated. The simplest way is to use a list, where
strings of station names in the path are stored in order. This list can then be displayed
using a simple for loop. Also, do not forget that you will need to display the total time it
takes to get from the origin to the destination.
In the end, you will need a list that contains the path and an integer which contains the
total time. So the evaluation section will need to produce that, but how?
Evaluate
We have considered the input and the output, now we just need to be able to actually
evaluate the shortest path. Since Dijkstra’s algorithm turns out to be quite a complex
algorithm, the most sensible thing to do is to break down the problem even further.
Data Structure
Before you start programming the Dijkstra’s algorithm, you need to create a data structure
that represents the graph which the program would use to perform the algorithm on. There
are many ways of doing this, and the choice depends on the programming language you
are using and also your personal preferences. However, for this project, we will focus on
one type of data structure - dictionary.
You should be familiar with Python lists as a sequence data structure. A list can contain
multiple elements which can be accessed with an integer index, starting from 0 for the first
item, 1 for the second item, and so on.
A dictionary works similarly to a list, but instead of having integer indexes for each
element, elements in a dictionary are indexed by keys, which can be of type string,
number, and other immutable types. You can think of it as a real dictionary, where all the
definitions (the elements) are indexed by the words defined by the definitions. Therefore,
every element in a dictionary must have both a key and a value; this is denoted as key :
value.
roman = {“one”: “I”, “five”: “V”, “ten”: “X”, “fifty”: “L”}
In the example above, the dictionary roman is defined with multiple key:value pairs that
represents the roman numerals. Note that dictionaries opens and ends with a curly bracket
and each key:value pair are separated by a comma. To access the elements in a
dictionary, you can use the square bracket syntax, just like with lists.
roman_ten = roman[“ten”] # roman_ten now has the value “X”
Also, just like you can put lists within lists, you can also put dictionaries inside dictionaries!
This can be extremely useful for our use case, as shown below.
graph = {“Euston Square”: {“Baker Street”: 5, “Kings Cross”: 2}}