feat(datastructures, graphs): clone graph#170
Conversation
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughAdds a new "Clone Graph" entry and README under datastructures/graphs/undirected, plus a Node class and a Changes
Sequence DiagramsequenceDiagram
participant Client
participant CloneFn as clone()
participant Helper as clone_helper()
participant Map as nodes_cloned (dict)
participant NewNode as Node (constructor)
Client->>CloneFn: clone(root)
CloneFn->>Map: initialize {}
CloneFn->>Helper: clone_helper(root, Map)
Helper->>Map: if node in Map?
alt not in Map
Helper->>NewNode: new Node(node.data)
NewNode-->>Helper: cloned_node
Helper->>Map: Map[node] = cloned_node
loop for each neighbor
Helper->>Map: is neighbor in Map?
alt not in Map
Helper->>Helper: recursive clone_helper(neighbor, Map)
Helper-->>Helper: cloned_neighbor
else
Map-->>Helper: cloned_neighbor
end
Helper->>cloned_node: append cloned_neighbor to neighbors
end
else
Map-->>Helper: return Map[node]
end
Helper-->>CloneFn: cloned_root
CloneFn-->>Client: return cloned_root
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@datastructures/graphs/undirected/clone_graph/__init__.py`:
- Around line 21-24: The check for whether a neighbour has been cloned uses a
truthiness test "if not cloned_neighbour" which is fragile; change it to an
explicit None check "if cloned_neighbour is None" when using
nodes_cloned.get(neighbour) inside clone_helper so that cloned_neighbour is only
treated as missing when truly None; update the condition around
cloned_node.neighbors += [clone_helper(neighbour, nodes_cloned)] to use "is
None" with the cloned_neighbour variable (and keep the existing logic that calls
clone_helper and appends the result).
- Around line 5-6: The signature types are misleading because clone accepts None
and clone_helper checks for None; update the type hints to reflect that by
changing the parameter types from Node to Optional[Node] for both clone(root:
Node) and the helper clone_helper(n: Node, nodes_cloned: Dict[Node, Node]), and
adjust any related variable annotations (e.g., nodes_cloned values/keys if
needed) so static type checkers accept None inputs for Node; keep the runtime
logic unchanged.
In `@datastructures/graphs/undirected/clone_graph/README.md`:
- Around line 52-60: Remove the blank line between the Example 2 and Example 3
blockquotes to fix MD028 and make formatting consistent; additionally, match
Example 3 to the other examples by either adding a preceding heading like "###
Example 3" or inserting the same image tag pattern used in Examples 1–2, and
include the missing example image/visual for the empty graph case (the block
referencing "adjList = []") so Example 3 follows the same structure as "Example
2" (which shows "adjList = [[]]") and the other examples in the README.
🧹 Nitpick comments (4)
DIRECTORY.md (1)
444-446: DIRECTORY.md entry only listsNode, missing the clone algorithm itself.The new entry links only to
node.py. Consider also listing the clone graph module (__init__.py) and/or theREADME.mdso the directory index reflects the full feature addition. If this file is auto-generated, disregard.datastructures/graphs/undirected/clone_graph/node.py (1)
4-7: Consider a more descriptive parameter name and a__repr__for debuggability.The constructor parameter
dis cryptic — renaming todataimproves readability. A__repr__method would simplify debugging and test output.♻️ Suggested improvement
class Node: - def __init__(self, d: Any): - self.data: Any = d + def __init__(self, data: Any): + self.data: Any = data self.neighbors: List["Node"] = [] + + def __repr__(self) -> str: + return f"Node(data={self.data})"datastructures/graphs/undirected/clone_graph/__init__.py (2)
32-34: Inconsistent variable naming:nodes_completedvsnodes_cloned.The outer function creates
nodes_completedbut the helper parameter is namednodes_cloned. Pick one name for consistency.Proposed fix
- nodes_completed: Dict[Node, Node] = {} - return clone_helper(root, nodes_completed) + nodes_cloned: Dict[Node, Node] = {} + return clone_helper(root, nodes_cloned)
24-28: Prefer.append()over+= [x]for adding single items.
+= [x]creates an intermediate list on each iteration..append(x)is more idiomatic and avoids the allocation.Proposed fix
- cloned_node.neighbors += [clone_helper(neighbour, nodes_cloned)] + cloned_node.neighbors.append(clone_helper(neighbour, nodes_cloned)) else: - cloned_node.neighbors += [cloned_neighbour] + cloned_node.neighbors.append(cloned_neighbour)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Describe your change:
Clone graph algorithm
Checklist:
Fixes: #{$ISSUE_NO}.Summary by CodeRabbit
New Features
Documentation