I’m implementing the Dijkstra search algorithm in Python. At the end of the search, I reconstruct the shortest path using a predecessor map, starting with the destination node’s predecessor. For example:
path = []
path.append(destination)
previous = predecessor_map[destination]
while previous != origin:
path.append(previous)
previous = predecessor_map[previous]
Is there any way to do this with less lines of code (e.g. list comprehension)?
The only suggestion that I have is to get rid of the slight code duplication:
Beyond that, I think your code is actually very clear and is unlikely to benefit from any attempts to shorten it.
Lastly, it is worth noting that the above also works when
destination == origin, whereas your original version most probably doesn’t (depends on how exactlypredecessor_mapis populated). Don’t know if this is relevant to your use cases.