[Python] Merging Overlapping Intervals

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    Currently, I have intervals of:

    temp_tuple = [[-25, -14], [-21, -16], [-20, -15], [-10, -7], [-8, -5], [-6, -3], [2, 4], [2, 3], [3, 6], [12, 15], [13, 18], [14, 17], [22, 27], [25, 30], [26, 29]]


    in an ascending order by the lower bound. My task is to merge overlapping intervals so that the outcome comes out to be:

    [-25, -14]
    [-10, -3]
    [2, 6]
    [12, 18]
    [22, 30]


    My first attempt involved deleting intervals that are completely within previous intervals, like [-21, -16] which falls within [-25, -14]. But deleting objects within a list kept interfering with the loop condition. My second attempt at deleting unnecessary intervals was:

    i = 0
    j = 1
    while i < len(temp_tuples):
    while j < len(temp_tuples):
    if temp_tuples[1] > temp_tuples[j][1]:
    del temp_tuples[j]
    j += 1
    i += 1


    but this doesn't delete all the unnecessary intervals for some reason. What should I do?

    Continue reading...

Compartilhe esta Página