Skip to content

Commit 0ffcc64

Browse files
authored
Merge pull request #10 from gjbex/copilot/fix-53eb5a18-6371-4fef-ab3b-e7fd003f7cfc
Refactor intersection tree to eliminate redundant validity checks in recursive methods
2 parents aba7c99 + e8f6d9e commit 0ffcc64

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

source_code/intersection_trees/intersection_tree.py

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,27 @@ def insert(self, interval: Interval) -> None:
6666
if interval[0] >= interval[1]:
6767
raise ValueError(f"Invalid interval: start ({interval[0]}) must be less than end ({interval[1]})")
6868

69+
self._insert(interval)
70+
71+
def _insert(self, interval: Interval) -> None:
72+
'''Private method to insert a new interval [start, end) in the tree.
73+
Does not validate the interval.
74+
75+
Parameters
76+
----------
77+
interval: Interval
78+
the interval to insert (assumed to be valid)
79+
'''
6980
if interval[0] < self._start:
7081
if self._left is None:
7182
self._left = Node(interval)
7283
else:
73-
self._left.insert(interval)
84+
self._left._insert(interval)
7485
else:
7586
if self._right is None:
7687
self._right = Node(interval)
7788
else:
78-
self._right.insert(interval)
89+
self._right._insert(interval)
7990
self._max_end = max(self._max_end, interval[1])
8091

8192
def search(self, interval: Interval, results: list[Interval]) -> None:
@@ -88,13 +99,34 @@ def search(self, interval: Interval, results: list[Interval]) -> None:
8899
the interval to search for intersections
89100
results: list[Interval]
90101
list to append the results to
102+
103+
Raises
104+
------
105+
ValueError
106+
if interval start is not less than end
107+
'''
108+
if interval[0] >= interval[1]:
109+
raise ValueError(f"Invalid interval: start ({interval[0]}) must be less than end ({interval[1]})")
110+
111+
self._search(interval, results)
112+
113+
def _search(self, interval: Interval, results: list[Interval]) -> None:
114+
'''Private method to search for all intervals in the tree that intersect with [start, end)
115+
and append them to results. Does not validate the interval.
116+
117+
Parameters
118+
----------
119+
interval: Interval
120+
the interval to search for intersections (assumed to be valid)
121+
results: list[Interval]
122+
list to append the results to
91123
'''
92124
if self._start < interval[1] and interval[0] < self._end:
93125
results.append((self._start, self._end))
94126
if self._left is not None and self._left._max_end >= interval[0]:
95-
self._left.search(interval, results)
127+
self._left._search(interval, results)
96128
if self._right is not None and self._right._max_end >= interval[0]:
97-
self._right.search(interval, results)
129+
self._right._search(interval, results)
98130

99131
def to_str(self, prefix: str = '') -> str:
100132
'''Return a string representation of the tree.

0 commit comments

Comments
 (0)