Skip to content

Instantly share code, notes, and snippets.

@boompig
Last active November 23, 2015 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boompig/57aeb5646be9962e1368 to your computer and use it in GitHub Desktop.
Save boompig/57aeb5646be9962e1368 to your computer and use it in GitHub Desktop.
class Interval(object):
def __init__(self, start, end, val):
self.start = start
self.end = end
self.val = val
def get_intersection(self, other):
"""Modify self and other to make non-overlapping intersections.
If there is another guy, return him. Otherwise return None.
Intervals can be changed to zero-length, which means they disappear."""
if self.end > other.start:
overlap_start = other.start
overlap_end = min(other.end, self.end)
overlap = Interval(overlap_start, overlap_end, self.val + other.val)
old_end = self.end
if self.end > other.end:
# shorten self
self.end = overlap.start
# change value of other
other.start = overlap.end
other.val = self.val
other.end = old_end
return overlap
else:
self.end = overlap.start
other.start = overlap.end
return overlap
else:
return None
def __repr__(self):
return "Interval (start={}, end={}, val={})".format(self.start, self.end, self.val)
def sort_interval_list(interval_list):
interval_list.sort(key=lambda interval: interval.start)
def get_over_limit(interval_list, limit):
sort_interval_list(interval_list)
i = 0
while i < len(interval_list) - 1:
o = interval_list[i].get_intersection(interval_list[i + 1])
if o is not None:
interval_list.insert(i + 1, o)
else:
i += 1
# so that when [i + 1] is modified, it is put in the right place
sort_interval_list(interval_list)
for i in range(len(interval_list)):
if interval_list[i].val > limit:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment