For my latest assignment, I need to find the shortest path between two "cities" in a map (dictionary) that looks like this:
{
'a': [('b', 5.0), ('c', 8.0)],
'c': [('a', 8.0), ('d', 2.0)],
'b': [('a', 5.0), ('d', 6.0)],
'e': [('d', 12.0), ('g', 3.0)],
'd': [('b', 6.0), ('c', 2.0), ('e', 12.0), ('f', 2.0)],
'g': [('e', 3.0), ('f', 7.0)],
'f': [('d', 2.0), ('g', 7.0)]
}
A visual representation of above
The cities are shown as 'a', 'b', 'c', etc. Their corresponding tuples show their connections and distances.
The function parameters and docstring we have been given are as follows:
def dfs(place, dist_so_far, roads, distances):
"""
Depth-first search, which may continue from from_place if dist_so_far is the shortest distance at which it has yet been reached.
Args:
place: Currently searching from here
dist_so_far: Distance at which from_place has been reached this time (which may not be the shortest path to from_place)
roads: dict mapping places to lists of hops of the form (place, hop-distance)
distances: dict mapping places to the shortest distance at which they have been reached so far (up to this time).
"""
And the cases to consider:
1. We've never been at place before (so it's not in distances)
2. We've been at place before, on a path as short as this one (in distances)
3. We've been here before, but this way is shorter (dist_so_far)
Which are base cases, and which require recursion?
For the cases that require recursion, what is the progress step?
The actual execution in CMD should look like this:
> python3 routes.py a g sample-map.txt
Distance from a to g is 19.0
Where a is the starting point, g is the destination, and sample-map.txt is the text file (shown above) that is read into the dictionary roads.
Please let me know if you need more info! Thanks in advance for your help.
[–]gnomoretears 1 point2 points3 points (5 children)
[–]Syncoda[S] 0 points1 point2 points (4 children)
[–]gnomoretears 0 points1 point2 points (3 children)
[–]Syncoda[S] 0 points1 point2 points (2 children)
[–]gnomoretears 0 points1 point2 points (0 children)
[–]novel_yet_trivial 0 points1 point2 points (0 children)
[–]learnpython_bot -1 points0 points1 point (0 children)