Created
January 14, 2020 21:24
-
-
Save jgomo3/ddb486cade9d5dc62b9b15a1f7e16d8c to your computer and use it in GitHub Desktop.
Merge periods or ranges in a collection of them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
>>> 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