Skip to content

Instantly share code, notes, and snippets.

Last active November 23, 2015 02:58
What would you like to do?
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
self.end = overlap.start
other.start = overlap.end
return overlap
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):
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)
i += 1
# so that when [i + 1] is modified, it is put in the right place
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