Skip to content

Instantly share code, notes, and snippets.

@jgomo3
Created January 14, 2020 21:24
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 jgomo3/ddb486cade9d5dc62b9b15a1f7e16d8c to your computer and use it in GitHub Desktop.
Save jgomo3/ddb486cade9d5dc62b9b15a1f7e16d8c to your computer and use it in GitHub Desktop.
Merge periods or ranges in a collection of them
'''
>>> periodos = [(3, 5), (7, 8), (11, 12), (-10, -1), (6, 10), (-2, 2)]
>>> periods_intersection((3, 5), (7, 8))
>>> periods_intersection((7, 8), (6, 10))
(7, 8)
>>> periods_intersection((-10, -1), (-2, 2))
(-2, -1)
>>> periods_union((-10, -1), (-2, 2))
(-10, 2)
>>> periods_union((6, 10), (7, 8))
(6, 10)
>>> list(sorted(unificar(periodos)))
[(-10, 2), (3, 5), (6, 10), (11, 12)]
'''
from functools import reduce
def periods_intersection(p1_, p2_):
p1, p2 = sorted((p1_, p2_))
return (p2[0], min(p1[1], p2[1])) if p1[1] >= p2[0] else None
def periods_union(p1_, p2_):
p1, p2 = sorted((p1_, p2_))
return (p1[0], max(p1[1], p2[1])) if p1[1] >= p2[0] else None
def unificar(periodos):
def append_intersection(partial_periods, next_period):
if partial_periods and periods_intersection(partial_periods[-1], next_period):
partial_periods[-1] = periods_union(partial_periods[-1], next_period)
else:
partial_periods.append(next_period)
return partial_periods
return reduce(append_intersection, sorted(periodos), [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment