find non-overlapping blocks in a list

I have a list: x = [[263, 3121], [2201, 4756], [3145, 6423], [4765, 8165], [12480, 18421], [18000, 24191], [26343, 28105], [27341, 28912], [29497, 30282]]

I want a new list that contains the merged overlapping blocks (highlighted above in bold): y = [[263,8165],[12480,24191],[26343,28912],[29497,30282]]

That is, to go through the x-list and merge all overlapping lists to give y. If the first item of the next item of the list in x is smaller than the last item of the previous item in x, then merge the two and save to y, otherwise don't merge just put the new starting value as the next item in y. Continue through x until all overlapping blocks are merged and written into y.

Thank you for your help


You can write down the code just as you described it in the text.

def yield_data(data):
    start = None
    end = None
    for entry in sorted(data):
        if start is None:
            start = entry[0]
        if end is None or entry[0] < end:
            end = entry[1]
            yield [start, end]
            start, end = entry
    yield [start, end]

def main():
    x = [[263, 3121], [2201, 4756], [3145, 6423], [4765, 8165], [12480, 18421],
         [18000, 24191], [26343, 28105], [27341, 28912], [29497, 30282]]
    for group in yield_data(x):

if __name__ == '__main__':

The compares to None are used to initialize the data in the first loop.

Need Your Help

ASP.NET MVC2 - Custom Model Binder Examples modelbinders custom-model-binder

I am trying to find some examples of building a custom model binder for a unique binding scenario I need to handle, but all of the articles I found were for older versions of MVC which are no longer

Writing/Reading text online

c# file-io httpwebrequest webclient

The title is rather inexplicit, but that’s because I’m open to almost any suggestions. Actually, I’m working on an XNA game project and I am working on implementing the possibility to choose a

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.