Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function contains infinite loops, and it seems everything is ok

I wrote function, that input array is list of intervals and returns nonoverlapping intervals.
Here is the function:

def mergeOverlappingIntervals(intervals):
    new=[]
    i=0
    while i <len(intervals):    
        if intervals[i][1]<intervals[i+1][0]:
            new.append(intervals[i])
            i+=1
        else:
            p1=i
            p2=i
            while intervals[i][1]<=intervals[i+1][0]:
              i+=1
              p2+=1
            new.append([intervals[p1][0],intervals[p2][1]])
            i=p2
    return new  

but this function contains infinite loops. It is unclear to me, why this function contains infinite loops and does not get expected outputs.
Example of inputs:

interval=[
    [1, 2],
    [3, 5],
    [4, 7],
    [6, 8],
    [9, 10]
  ]

outputs=[
  [1, 2],
  [3, 8],
  [9, 10]
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your inner while loop uses the wrong condition. You want to merge two intervals when intervals[i][1] is greater than or equal to, not less than or equal to, intervals[i+1][0].

while intervals[i][1] >= intervals[i+1][0]:
    i += 1
    p2 += 1

There may be other issues, but this one stands out as the primary problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading