Skip to content

Commit

Permalink
Early out in overlaps/contains
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreDecan committed Sep 14, 2021
1 parent 2bccd0e commit d352af6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Speed up lookups in `IntervalDict` ([#65](https://github.com/AlexandreDecan/portion/issues/65), Jeff Trull).
- Speed up removals in `IntervalDict`.
- Speed up intersection for non-overlapping intervals ([#66](https://github.com/AlexandreDecan/portion/issues/66), Jeff Trull).
- Speed up `.overlaps` and `.contains` for non-overlapping intervals/items.



Expand Down
10 changes: 10 additions & 0 deletions portion/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,10 @@ def overlaps(self, other):
:return: True if intervals overlap, False otherwise.
"""
if isinstance(other, Interval):
if self.upper < other.lower or self.lower > other.upper:
# Early out for clearly non-overlapping intervals
return False

i_iter = iter(self)
o_iter = iter(other)
i_current = next(i_iter)
Expand Down Expand Up @@ -523,6 +527,9 @@ def __contains__(self, item):
if isinstance(item, Interval):
if item.empty:
return True
elif self.upper < item.lower or self.lower > item.upper:
# Early out for non-overlapping intervals
return False
elif self.atomic:
left = item.lower > self.lower or (
item.lower == self.lower
Expand All @@ -549,6 +556,9 @@ def __contains__(self, item):
return False
return True
else:
if self.upper < item or self.lower > item:
return False

# Item is a value
for i in self._intervals:
left = (item >= i.lower) if i.left == Bound.CLOSED else (item > i.lower)
Expand Down

0 comments on commit d352af6

Please sign in to comment.