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

updated topological_sort.py #11287

Closed
wants to merge 20 commits into from
Closed
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
9b7e9e1
Update topological_sort.py
ShengLiuDev Feb 12, 2024
fe22fb2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 12, 2024
ad74538
Update topological_sort.py
ShengLiuDev Feb 12, 2024
2d1622f
Merge branch 'master' of https://github.com/ShengLiuDev/TheAlgorithms…
ShengLiuDev Feb 12, 2024
0a8383b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 12, 2024
fecee82
Update topological_sort.py
ShengLiuDev Feb 12, 2024
047ddd2
Merge branch 'master' of https://github.com/ShengLiuDev/TheAlgorithms…
ShengLiuDev Feb 12, 2024
029c12f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 12, 2024
96232dd
Fixed Camel Casing
ShengLiuDev Feb 12, 2024
aace5a0
Merge branch 'master' of https://github.com/ShengLiuDev/TheAlgorithms…
ShengLiuDev Feb 12, 2024
ed0e152
Fixed capitalization
ShengLiuDev Feb 12, 2024
b3e467c
Added as keyword
ShengLiuDev Feb 12, 2024
81bbdd3
got rid of import
ShengLiuDev Feb 12, 2024
c5fc2a1
Any import
ShengLiuDev Feb 12, 2024
d2eafae
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 12, 2024
ae7ae96
removed any
ShengLiuDev Feb 12, 2024
05eb625
Merge branch 'master' of https://github.com/ShengLiuDev/TheAlgorithms…
ShengLiuDev Feb 12, 2024
78af49e
rewrote to list
ShengLiuDev Feb 12, 2024
505e448
Update topological_sort.py
ShengLiuDev Feb 12, 2024
fae8f10
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 264 additions & 8 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Topological Sort."""

# Test cases:

# a
# / \
# b c
Expand All @@ -15,27 +17,281 @@
vertices: list[str] = ["a", "b", "c", "d", "e"]


def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
"""Perform topological sort on a directed acyclic graph."""
# a
# / | \
# b c f
# / \ / \
# d e g h
# /
# i
edges: dict[str, list[str]] = {
"a": ["b", "c", "f"],
"b": ["d", "e"],
"c": [],
"d": [],
"e": [],
"f": ["g", "h"],
"g": ["i"],
"h": [],
"i": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

# a
# / \
# b c
# / / \
# d e f
# /
# g
# /
# h
# /
# i
# /
# j
# /
# k
edges: dict[str, list[str]] = {
"a": ["b", "c"],
"b": ["d"],
"c": ["e", "f"],
"d": ["g"],
"e": [],
"f": [],
"g": ["h"],
"h": ["i"],
"i": ["j"],
"j": ["k"],
"k": [],
}

vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]


#
# a
# / \
# b c
# / \ / \
# d e f g
edges: dict[str, list[str]] = {
"a": ["b", "c"],
"b": ["d", "e"],
"c": ["f", "g"],
"d": [],
"e": [],
"f": [],
"g": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g"]

#
# a
# / \
# b c
# / \ / \
# d e f g
# / \ \ \
# h i j k
# / \
# l m
# /
# n
#
#
edges: dict[str, list[str]] = (
{
"a": ["b", "c"],
"b": ["d", "e"],
"c": ["f", "g"],
"d": ["h", "i"],
"e": ["j"],
"f": [],
"g": ["k"],
"h": ["l"],
"i": ["m"],
"j": [],
"k": [],
"l": ["n"],
"m": [],
"n": [],
},
)
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g"]

# a
# /
# b
# /
# c
# /
# d
# /
# e
# /
# f
# /
# g
# /
# h
edges: dict[str, list[str]] = {
"a": ["b"],
"b": ["c"],
"c": ["d"],
"d": ["e"],
"e": ["f"],
"f": ["g"],
"g": ["h"],
"h": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h"]

# a
# / | \
# b c d
# / \
# e f
# / \
# g h
# / \
# i j
# / \
# k l
edges: dict[str, list[str]] = {
"a": ["b", "c", "d"],
"b": ["e"],
"c": [],
"d": ["f"],
"e": ["g"],
"f": ["h"],
"g": ["i"],
"h": ["j"],
"i": ["k"],
"j": ["l"],
"k": [],
"l": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

# a
# / \
# b c
# / \
# d e
edges: dict[str, list[str]] = {
"a": ["b", "c"],
"b": ["d"],
"c": ["e"],
"d": [],
"e": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e"]


# a h
# / \ \
# b c i
# | | |
# d e j
# | |
# g f
edges: dict[str, list[str]] = {
"a": ["b", "c"],
"b": ["d"],
"c": ["e", "f"],
"d": ["g"],
"e": [],
"f": [],
"g": [],
"h": ["i"],
"i": ["j"],
"j": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

# a h k
# / \ \ \
# b c i l
# | | | |
# d e j m
# | |
# g f
edges: dict[str, list[str]] = {
"a": ["b", "c"],
"b": ["d"],
"c": ["e"],
"d": ["g"],
"e": ["f"],
"f": [],
"g": [],
"h": ["i"],
"i": ["j"],
"j": [],
"k": ["l"],
"l": ["m"],
"m": [],
}
vertices: list[str] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]


def topological_sort_util(
start: str, edges: dict[str, list[str]], visited: list[str], sort: list[str]
) -> list[str]:
""""""
"""
Examples:
>>> topological_sort(['a', 'b', 'c', 'd'], {"a": ["b", "c"], "b": ["d"], "c": [], "d": []})

Check failure on line 244 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:244:89: E501 Line too long (95 > 88)

Check failure on line 244 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:244:89: E501 Line too long (95 > 88)
['d', 'c', 'b', 'a']
>>> topological_sort(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], {"a": ["b"], "b": ["c"], "c": ["d"], "d": ["e"], "e": ["f"], "f": ["g"], "g": ["h"], "h": []})

Check failure on line 246 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:246:89: E501 Line too long (161 > 88)

Check failure on line 246 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:246:89: E501 Line too long (161 > 88)
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> topological_sort(['a', 'b', 'c', 'd', 'e', 'f', 'g'], {"a": ["b", "c"], "b": ["d", "e"], "c": ["f", "g"], "d": [], "f": [], "h": []})

Check failure on line 248 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:248:89: E501 Line too long (141 > 88)

Check failure on line 248 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:248:89: E501 Line too long (141 > 88)
['d', 'f', 'e', 'g', 'c', 'b', 'a']
>>> topological_sort([], {})
['']
"""

current = start
# add current to visited
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
sort = topological_sort_util(neighbor, edges, visited, sort)
# if all neighbors visited add current to sort
sort.append(current)
# if all vertices haven't been visited select a new one to visit
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)
if len(visited) != len(edges):
for vertex in edges:
if vertex not in visited:
sort = topological_sort_util(vertex, edges, visited, sort)
# return sort
return sort


def topological_sort(vertices: list[str], edges: dict[str, list[str]]) -> list[str]:
sort = []
visited = []
for vertex in vertices:
if vertex not in visited:
sort = topological_sort_util(vertex, edges, visited, sort)
return sort


if __name__ == "__main__":
sort = topological_sort("a", [], [])
# Get vertices from the user
vertices_input = input("Please enter the vertices separated by commas: ").strip()
vertices = [vertex.strip() for vertex in vertices_input.split(",")]
# Initialize an empty dictionary for edges
edges = {}
# Iterate over each vertex to get its connected edges
for vertex in vertices:
edges_input = input(
f'Please enter the edges connected to vertex "{vertex}" separated by commas (leave empty to finish): '

Check failure on line 291 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:291:89: E501 Line too long (114 > 88)

Check failure on line 291 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:291:89: E501 Line too long (114 > 88)
).strip()
edges[vertex] = [
edge.strip() for edge in edges_input.split(",") if edge.strip()
]
sort = topological_sort(vertices, edges)
print(sort)
Loading