Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save qubard/8d9cad676fec9601ba2915cb1dfa8fbd to your computer and use it in GitHub Desktop.

Select an option

Save qubard/8d9cad676fec9601ba2915cb1dfa8fbd to your computer and use it in GitHub Desktop.
overlap_intervals_units.py
intervals = [(200,300),(300,500),(550,600)]
def overlap(A,B):
"""Does the range (start1, end1) overlap with (start2, end2)?"""
start1,end1 = A
start2,end2 = B
return (
start1 <= start2 <= end1 or
start1 <= end2 <= end1 or
start2 <= start1 <= end2 or
start2 <= end1 <= end2
)
# make sure input intervals are sorted by first coord
def overlap_units(interval, intervals):
A, B = interval
units = 0
for i in range(0, len(intervals)):
p = intervals[i]
X,Y = p
if overlap((A,B),p): # just check if they overlap at all
if B <= Y: # intersects completely
# units +=
Z, K = (max(X,A), B)
units += K-Z+1
return units
# doesnt consume entire interval
# ie intersects partially
Z, K = (max(X,A), min(Y,B))
units += K-Z+1
# shift start point of interval
A = K
return units
print(overlap_units((300,400),intervals))
print(overlap_units((250,400),intervals))
print(overlap_units((200,600),intervals))
print(overlap_units((520,540),intervals))
print(overlap_units((0,1000),intervals))
print(overlap_units((-100,200),intervals))
print(overlap_units((-100,199),intervals))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment