refactor: ⚡️ Speed up function find_last_node by 29,891% (#5261)
⚡️ Speed up function `find_last_node` by 29,891%
Certainly! We can optimize the existing code by minimizing the checks inside the loop and improving the lookup operations. Here's an optimized version of the program.
### Explanation.
1. **Set for Fast Lookup**: We first create a set of all source IDs from the edges. This is efficient because checking for membership in a set is on average O(1) time complexity.
2. **Iterate Through Nodes**: We loop through each node and check if its ID is not in the set of source IDs. If a node's ID is not found in the set, it means this node has no outgoing edges and is the "last node".
This approach ensures we only iterate over the edges once to create the set and then do a fast lookup for each node, improving the overall efficiency.
Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
This commit is contained in:
parent
cd602c8403
commit
e8d3714dc6
1 changed files with 5 additions and 1 deletions
|
|
@ -24,7 +24,11 @@ def find_start_component_id(vertices):
|
|||
|
||||
def find_last_node(nodes, edges):
|
||||
"""This function receives a flow and returns the last node."""
|
||||
return next((n for n in nodes if all(e["source"] != n["id"] for e in edges)), None)
|
||||
source_ids = {edge["source"] for edge in edges}
|
||||
for node in nodes:
|
||||
if node["id"] not in source_ids:
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def add_parent_node_id(nodes, parent_node_id) -> None:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue