Fix topological sort order#14609
Conversation
| sort = topological_sort(neighbor, visited, sort) | ||
| # if all neighbors visited add current to sort | ||
| sort.append(current) | ||
| # if all neighbors visited add current before its descendants |
There was a problem hiding this comment.
This comment seems inaccurate. At this point, the DFS has already visited all reachable descendants, and current is being inserted before them in the final ordering. Consider rewording it to avoid confusion.
| # if all neighbors visited add current to sort | ||
| sort.append(current) | ||
| # if all neighbors visited add current before its descendants | ||
| sort.insert(0, current) |
There was a problem hiding this comment.
Using insert(0, current) fixes the ordering, but it is O(n) for every insertion. For larger graphs, consider appending during DFS and reversing once at the end for better performance.
| # if all neighbors visited add current before its descendants | ||
| sort.insert(0, current) | ||
| # if all vertices haven't been visited select a new one to visit | ||
| if len(visited) != len(vertices): |
There was a problem hiding this comment.
This function depends on the global vertices list, which makes it less reusable. Consider passing vertices as a parameter instead of relying on module-level state.
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sort = topological_sort("a", [], []) |
There was a problem hiding this comment.
Consider adding a small assertion-based test instead of only printing the result. That would make it easier to verify the corrected topological order automatically.
Describe your change:
Fixes #12192.
topological_sort()was appending each vertex after visiting its descendants, so the returned list was the reverse of the intended topological order. This keeps the existing DFS structure and inserts each completed vertex at the front of the result instead, so parents appear before their descendants.Verified example output:
Checklist:
Local verification:
python3 sorts/topological_sort.pyruff check sorts/topological_sort.pyruff format --check sorts/topological_sort.pygit diff --checkNote:
python3 -m pytest sorts/topological_sort.pycollects no tests because this existing file has no doctests.