延长任何中断长度的间隔,直到达到其原始长度

Extending an interval for the length of any interruption until its original length is reached

假设我有以下间隔,存储为列表:

main_iv = [10, 30]

和以下中断(重叠)上述间隔的间隔:

break_iv = [[8, 12], [15, 18], [32, 40], [42, 43]]

我想延长 main_iv 直到它完全达到其原始长度 (20),再次考虑延长期间发生的任何中断。

我有第一次中断的工作代码,但我真的很难找到一种方法使它连续动态地工作,以应对未指定数量的中断。

def overlap_calc(start_1, start_2, end_1, end_2):
        latest_start = max(start_1, start_2)
        earliest_end = min(end_1, end_2)
        delta = (earliest_end - latest_start) + 1
        overlap = max(0, delta)
        return(overlap)

main_iv = [10, 30]

break_iv = [[8, 12], [15, 18], [32, 40]]

overlap = 0
for sub_iv in break_iv:
    overlap += overlap_calc(main_iv[0], sub_iv[0], main_iv[1], sub_iv[1])

main_iv[1] = main_iv[1] + overlap

print(main_iv)

这给出了以下输出,其中考虑了重叠 [8, 12](3 的重叠)和 [15, 18](4 的重叠):

[10, 37]

但是考虑到区间[32, 40]再次与扩展重叠(运行从3137),原来的区间只能在之后完成40. 因此,预期的输出将如下所示:

[10, 46]

如果我正确理解你的问题,你可以这样做。

def solve(main, gaps):
    start, end = main
    for lo, hi in gaps:
        if hi < start:
            # gap is lower than main
            continue
        if lo > end:
            # gap is higher than main
            break
        # extend main end by overlap length
        overlap_length = hi + 1 - max(lo, start)
        end += overlap_length
        
    return [start, end]

这给出了预期的结果,假设间隙之间没有重叠,并且间隙按升序排列。

>>> solve(main=(10,30), gaps=[(8,12), (15,18), (32,40)])
[10, 46]