Last active
July 8, 2021 09:42
-
-
Save W4RH4WK/d28dbfe12291a746c9cd605fd3e31e6d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from datetime import datetime | |
from typing import List | |
class DatetimeInterval: | |
def __init__(self, start, end): | |
self.start = start | |
self.end = end | |
def __lt__(self, other): | |
return (self.start, self.end) < (other.start, other.end) | |
def __str__(self): | |
return f'{self.start} - {self.end}' | |
def merge_overlaps(records: List[DatetimeInterval]) -> List[DatetimeInterval]: | |
if not records: | |
return [] | |
# Ensure chronolocial order. | |
records.sort() | |
result = [] | |
current = DatetimeInterval(records[0].start, records[0].end) | |
for record in records: | |
if record.start <= current.end: | |
current.end = max(current.end, record.end) | |
else: | |
result.append(current) | |
current = DatetimeInterval(record.start, record.end) | |
# Don't forget about the last one! | |
result.append(current) | |
return result | |
records = [ | |
# Case 1: Standalone interval. | |
DatetimeInterval(datetime.fromisoformat('2021-01-01 11:00'), datetime.fromisoformat('2021-01-01 12:30')), | |
# Case 2: Second interval enclosed in first interval. | |
DatetimeInterval(datetime.fromisoformat('2021-01-01 10:00'), datetime.fromisoformat('2021-01-01 10:30')), | |
DatetimeInterval(datetime.fromisoformat('2021-01-01 10:10'), datetime.fromisoformat('2021-01-01 10:15')), | |
# Case 3: Second interval extends first interval. | |
DatetimeInterval(datetime.fromisoformat('2021-01-01 14:00'), datetime.fromisoformat('2021-01-01 14:30')), | |
DatetimeInterval(datetime.fromisoformat('2021-01-01 14:10'), datetime.fromisoformat('2021-01-01 14:40')), | |
] | |
result = merge_overlaps(records) | |
for record in result: | |
print(record) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment