Skip to content

Commit 0401124

Browse files
committed
add doctest
1 parent 9725d2c commit 0401124

1 file changed

Lines changed: 28 additions & 1 deletion

File tree

data_structures/binary_tree/segment_tree_node.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ def build(self, start: int, end: int, nums: list[int]) -> Node:
3030
:param end: End index of the segment.
3131
:param nums: Original input array.
3232
:return: Root node of the constructed subtree.
33+
34+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="max")
35+
>>> tree.root.value
36+
5
3337
"""
3438
if start > end:
3539
return Node(0, 0)
@@ -57,6 +61,10 @@ def max_in_range(self, start_index: int, end_index: int) -> int:
5761
"""
5862
Queries the maximum value in a given range.
5963
Only works in 'max' mode.
64+
65+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="max")
66+
>>> tree.max_in_range(1, 3)
67+
4
6068
"""
6169
if self.mode == "sum":
6270
raise Exception("Current Segment Tree doesn't support finding max")
@@ -73,6 +81,10 @@ def sum_in_range(self, start_index: int, end_index: int) -> int:
7381
"""
7482
Queries the sum of values in a given range.
7583
Only works in 'sum' mode.
84+
85+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="sum")
86+
>>> tree.sum_in_range(1, 3)
87+
9
7688
"""
7789
if self.mode == "max":
7890
raise Exception("Current Segment Tree doesn't support summing")
@@ -96,6 +108,10 @@ def query(
96108
:param start: Node's segment start.
97109
:param end: Node's segment end.
98110
:return: Result of query in the range.
111+
112+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="max")
113+
>>> tree.query(tree.root, 1, 3, 0, 4)
114+
4
99115
"""
100116
# Complete overlap
101117
if start_index <= start and end <= end_index:
@@ -124,6 +140,11 @@ def update(self, index: int, new_value: int) -> None:
124140
Updates a value at a specific index in the segment tree.
125141
:param index: Index to update.
126142
:param new_value: New value to set.
143+
144+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="max")
145+
>>> tree.update(2, 6)
146+
>>> tree.max_in_range(1, 3)
147+
6
127148
"""
128149
if index < 0 or index >= self.size:
129150
raise Exception("Invalid index")
@@ -140,6 +161,11 @@ def modify(
140161
:param new_value: New value to assign.
141162
:param start: Start index of node's segment.
142163
:param end: End index of node's segment.
164+
165+
>>> tree = SegmentTree([1, 2, 3, 4, 5], mode="max")
166+
>>> tree.modify(tree.root, 2, 6, 0, 4)
167+
>>> tree.max_in_range(0, 4)
168+
6
143169
"""
144170
if start == end:
145171
node.value = new_value
@@ -156,4 +182,5 @@ def modify(
156182
if self.mode == "max":
157183
node.value = max(node.left.value, node.right.value)
158184
else:
159-
node.value = node.left.value + node.right.value
185+
node.value = node.left.value + node.right.value
186+

0 commit comments

Comments
 (0)