Skip to content

Fix topological sort order#14609

Open
Kcstring wants to merge 2 commits intoTheAlgorithms:masterfrom
Kcstring:fix-topological-sort-order
Open

Fix topological sort order#14609
Kcstring wants to merge 2 commits intoTheAlgorithms:masterfrom
Kcstring:fix-topological-sort-order

Conversation

@Kcstring
Copy link
Copy Markdown

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:

['a', 'b', 'e', 'd', 'c']
  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

Local verification:

  • python3 sorts/topological_sort.py
  • ruff check sorts/topological_sort.py
  • ruff format --check sorts/topological_sort.py
  • git diff --check

Note: python3 -m pytest sorts/topological_sort.py collects no tests because this existing file has no doctests.

@algorithms-keeper algorithms-keeper Bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed labels Apr 29, 2026
Comment thread sorts/topological_sort.py Outdated
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
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread sorts/topological_sort.py Outdated
# if all neighbors visited add current to sort
sort.append(current)
# if all neighbors visited add current before its descendants
sort.insert(0, current)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread sorts/topological_sort.py Outdated
# 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):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread sorts/topological_sort.py Outdated
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread sorts/topological_sort.py
sort = topological_sort(vertice, visited, sort)
# return sort
_visit(vertice, visited, sort, graph)
sort.reverse()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is the core fix — adding sort.reverse() correctly produces
topological order since DFS post-order appends nodes after all
descendants are visited, giving reverse topological order.

Worth adding a brief comment explaining why the reverse is needed
so future readers understand the intent:

Post-order DFS gives reverse topological order, so reverse to fix

sort.reverse()

Comment thread sorts/topological_sort.py
"""Perform topological sort on a directed acyclic graph."""
current = start
# add current to visited
def _visit(
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Good refactor extracting _visit() as a private helper — separating
the DFS traversal from the main topological_sort() logic makes both
functions easier to understand and test independently.

One suggestion: _visit() modifies visited and post_order in place
via side effects but has no doctest. Since it's a private helper
this is acceptable, but a one-line docstring explaining the side
effects would help:

def _visit(current, visited, post_order, graph):
"""DFS helper — appends nodes to visited and post_order in place."""

Comment thread sorts/topological_sort.py
start: str,
visited: list[str],
sort: list[str],
graph: dict[str, list[str]] | None = None,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Using mutable default arguments as None with an explicit check on
lines 50-53 is the correct Python pattern — good call avoiding the
classic mutable default argument trap.

However the parameter name "sort" on line 35 is a bit confusing
since "sort" is also a Python built-in. Consider renaming to
"result" or "order" to avoid shadowing and improve readability:

def topological_sort(
start: str,
visited: list[str],
order: list[str], # renamed from "sort"
graph: dict[str, list[str]] | None = None,
vertices_list: list[str] | None = None,
) -> list[str]:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

topological sort returns reversed list

3 participants