Skip to content

Commit

Permalink
Optimized Range.overlap, 1.25x speedup.
Browse files Browse the repository at this point in the history
  • Loading branch information
runfalk committed Mar 22, 2017
1 parent c67ef1e commit f865e4d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
3 changes: 2 additions & 1 deletion doc/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ This release is a preparation for a stable 1.0 release.

- Renamed classes to match :pep:`8#class-names` conventions. This does not apply
to classes that works on built-in that does not follow :pep:`8#class-names`.
- Optimized :meth:`~spans.types.Range.union`, 1.3x speedup.
- Optimized :meth:`~spans.types.Range.overlap`, 1.3x speedup.
- Optimized :meth:`~spans.types.Range.union`, 1.25x speedup.


Version 0.4.0
Expand Down
11 changes: 10 additions & 1 deletion spans/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,16 @@ def overlap(self, other):
See also :meth:`~spans.types.Range.intersection`.
"""

return not self << other and not other << self
if self < other:
a, b = self, other
else:
a, b = other, self

# We need to explicitly handle unbounded ranges since a.upper and b.lower
# make the intervals seem adjacent even though they are not
if a.upper_inf or b.lower_inf:
return True
return a.upper > b.lower or a.upper == b.lower and a.upper_inc and b.lower_inc

def adjacent(self, other):
"""
Expand Down
16 changes: 10 additions & 6 deletions tests/test_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,21 +291,25 @@ def test_within_type_check(value):


@pytest.mark.parametrize("a, b", [
(intrange(1, 5, upper_inc=True), intrange(5, 10)),
(intrange(1, 5), intrange(3, 8)),
(intrange(3, 8), intrange(1, 5)),
(intrange(1, 10), intrange(5)),
(floatrange(1.0, 5.0, upper_inc=True), floatrange(5.0, 10.0)),
(floatrange(1.0, 5.0), floatrange(3.0, 8.0)),
(floatrange(1.0, 10.0), floatrange(5.0)),
(floatrange(upper=10.0), floatrange(1.0, 5.0)),
(floatrange(1.0), floatrange()),
])
def test_overlap(a, b):
assert a.overlap(b)
assert b.overlap(a)


@pytest.mark.parametrize("a, b", [
(intrange(1, 5), intrange(5, 10)),
(intrange(1, 5), intrange(5, 10, lower_inc=False)),
(floatrange(1.0, 5.0), floatrange(5.0, 10.0)),
(floatrange(1.0, 5.0), floatrange(5.0, 10.0, lower_inc=False)),
(floatrange(upper=5.0), floatrange(5.0)),
])
def test_not_overlap(a, b):
assert not a.overlap(b)
assert not b.overlap(a)


@pytest.mark.parametrize("a, b", [
Expand Down

0 comments on commit f865e4d

Please sign in to comment.