Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "merge" method into IntervalSet class. #22

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions pyinter/interval_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,24 @@ def difference(self, other):
def complement(self):
intersection = lambda a, b: a.intersection(b)
return functools.reduce(intersection, [interval.complement() for interval in list(self)])

def merge(self):
"""
Merge overlapping intervals
For example, {(0,3), (3,6), (5,10]} => {(0,3), (3,10]}
"""
result = IntervalSet()
if self.empty():
return result
sorted_intervals = sorted(self._data)
now = sorted_intervals[0]
for interval in sorted_intervals[1:]:
if now.upper_value<interval.lower_value or \
(now.upper_value==interval.lower_value and now.upper==0 and interval.lower==0):
result._data.add(now.copy())
now = interval
else:
now.upper_value = interval.upper_value
now.upper = interval.upper
result._data.add(now.copy())
return result
4 changes: 4 additions & 0 deletions tests/test_interval_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,7 @@ def test_repr():
def test_comparison_raises_not_implemented_error_if_it_cannot_compare():
with pytest.raises(NotImplementedError):
IntervalSet() == 1

def test_merge():
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test doesn't call the new merge function & should pass without your change

interval_set = IntervalSet([i.open(0, 3), i.open(3, 6), i.closed(5, 10)])
assert repr(interval_set) == 'IntervalSet((0, 3), (3, 10])'