而不是查询具有开始和结束日期的间隔列表以从列表中检索仅与搜索开始和结束日期重叠的所有间隔,最好的方法是:
From a list of date intervals,
Find all unique sets of intervals
Where every interval in each set overlaps with each other interval in that set
使用整数示例,获取整数区间列表[{1,3},{2,4},{4,5},{5,7},{6,8}]
。从此列表中,以下是所有独特的间隔集,其中每个集中的每个间隔都相互重叠:
{ {1,3}, {2,4} }
{ {2,4}, {4,5} }
{ {4,5}, {5,7} }
{ {5,7}, {6,8} }
这是 DateInterval 的类:
from datetime import datetime
class DateInterval(object):
def __init__(self, start_time, end_time):
self.start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
seld.end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
''' eq, gt, hash methods removed for clarity '''
我将收到按 start_time 升序排序的间隔列表,如下所示:
intervals = [DateInterval(start_time='2015-01-01 08:00:00', end_time='2015-01-01 08:30:00'),
DateInterval(start_time='2015-01-01 08:00:00', end_time='2015-01-01 10:00:00'),
DateInterval(start_time='2015-01-01 09:00:00', end_time='2015-01-01 11:00:00'),
DateInterval(start_time='2015-01-01 10:00:00', end_time='2015-01-01 12:00:00'),
DateInterval(start_time='2015-01-01 13:00:00', end_time='2015-01-01 16:00:00'),
DateInterval(start_time='2015-01-01 14:00:00', end_time='2015-01-01 17:00:00'),
DateInterval(start_time='2015-01-01 15:00:00', end_time='2015-01-01 18:00:00'),
DateInterval(start_time='2015-01-01 20:00:00', end_time='2015-01-01 22:00:00'),
DateInterval(start_time='2015-01-01 20:00:00', end_time='2015-01-01 22:00:00')
]
(在这个示例列表中,开始日期和结束日期总是均匀地落在一个小时上。但是,它们可以改为任何秒(或者可能是毫秒))。在搜索关于重叠间隔的详尽问题列表后,我发现间隔树不适合 Date Intervals)。
我轻微优化的蛮力方法包括三个任务
- 识别所有非唯一的区间集,其中每组中的至少一个区间与该集中的所有其他区间重叠
- 对步骤 1 的结果进行重复数据删除,以找到所有唯一的区间集,其中每组中的至少一个区间与该组中的所有其他区间重叠
- 从 1 的结果中,仅找到一个集合中的每个区间与该集合中的所有其他区间重叠的那些集合
1.
下面通过天真地将区间列表中的每个区间与所有其他区间进行比较,找到所有非唯一集合,其中每个集合中只有一个区间与该集合中的每个其他区间重叠。它假设间隔列表按日期时间升序排序,这可以break
优化
def search(intervals, start_date, end_date):
results = []
for interval in intervals:
if end_date >= interval.start_time:
if start_date <= interval.end_time:
results.append(interval)
else:
break # This assumes intervals are sorted by date time ascending
search
像这样使用:
brute_overlaps = []
for interval in intervals:
brute_overlaps.append(search(intervals, interval.start_time, interval.end_time))
2.
以下对集合列表进行重复数据删除:
def uniq(l):
last = object()
for item in l:
if item == last:
continue
yield item
last = item
def sort_and_deduplicate(l):
return list(uniq(sorted(l, reverse=True)))
3.
下面通过天真地将集合中的每个间隔与该集合中的每个其他间隔进行比较,找到每个集合中的每个间隔与该集合中的所有其他间隔重叠的所有集合:
def all_overlap(overlaps):
results = []
for overlap in overlaps:
is_overlap = True
for interval in overlap:
for other_interval in [o for o in overlap if o != interval]:
if not (interval.end_time >= other_interval.start_time and interval.start_time <= other_interval.end_time):
is_overlap = False
break # If one interval fails
else: # break out of
continue # both inner for loops
break # and try next overlap
if is_overlap: # all intervals in this overlap set overlap with each other
results.append(overlap)
return results