refactor: ️ Speed up function find_cycle_vertices by 324% (#5262)

This commit is contained in:
Saurabh Misra 2024-12-16 18:33:37 -08:00 committed by GitHub
commit a97c29fb39
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -435,13 +435,14 @@ def should_continue(yielded_counts: dict[str, int], max_iterations: int | None)
def find_cycle_vertices(edges):
# Create a directed graph from the edges
graph = nx.DiGraph(edges)
# Find all simple cycles in the graph
cycles = list(nx.simple_cycles(graph))
# Initialize a set to collect vertices part of any cycle
cycle_vertices = set()
# Flatten the list of cycles and remove duplicates
cycle_vertices = {vertex for cycle in cycles for vertex in cycle}
# Utilize the strong component feature in NetworkX to find cycles
for component in nx.strongly_connected_components(graph):
if len(component) > 1 or graph.has_edge(tuple(component)[0], tuple(component)[0]): # noqa: RUF015
cycle_vertices.update(component)
return sorted(cycle_vertices)