Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Dijkstra's to use set #10

Merged
merged 2 commits into from
Mar 27, 2024
Merged

Conversation

Takashiidobe
Copy link
Contributor

@Takashiidobe Takashiidobe commented Mar 27, 2024

Some changes reviewing the dijkstra's shortest path algo

ref: #9

@@ -18,27 +17,25 @@ def make_graph():

def dijkstras_heap(G, start='A'):
shortest_paths = {}
visited = {}
visited = set()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is the change noted in the issue about representing the set as a dict when a set would do.

heap = []

for node in list(G.keys()):
for node in G.keys():
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

G.keys() is an iterator, so there's no need to turn it into a list.

@@ -47,7 +44,7 @@ def dijkstras_heap(G, start='A'):

def dijkstras(G, start='A'):
shortest_paths = {}
unvisited = list(G.keys())
unvisited = dict.fromkeys(G.keys())
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code used to be a list, which would then call remove on min_node in a loop. There's no guarantee that min_node is at the end of the list, so remove has to do a seek to find the min_node in the list and remove it, and both operations are O(n).

If it's changed to a dictionary, finding the min_node is O(1) and removing it is also O(1).

shortest_path/dijkstras.py Outdated Show resolved Hide resolved
shortest_path/dijkstras.py Outdated Show resolved Hide resolved
Copy link
Owner

@msambol msambol left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two nits otherwise looks great.

@msambol msambol changed the title changes for dijkstra's algorithm code Update Dijkstra's to use set Mar 27, 2024
Copy link
Owner

@msambol msambol left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @Takashiidobe!

@msambol msambol merged commit c5dd4af into msambol:master Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants