Is a merge interval function available?

Nobody nobody at nowhere.com
Wed Feb 10 22:48:05 EST 2010


On Wed, 10 Feb 2010 15:23:42 -0800, Peng Yu wrote:

> I'm wondering there is already a function in python library that can
> merge intervals. For example, if I have the following intervals ('['
> and ']' means closed interval as in
> http://en.wikipedia.org/wiki/Interval_(mathematics)#Excluding_the_endpoints)
> 
> [1, 3]
> [2, 9]
> [10,13]
> [11,12]
> 
> I want to get the following merged intervals.
> 
> [1,9]
> [10,13]
> 
> Could somebody let me know if there is a function in the python
> library?

No, but try this:

def merge(intervals):
    if not intervals:
	return []
    intervals = sorted(intervals, key = lambda x: x[0])
    result = []
    (a, b) = intervals[0]
    for (x, y) in intervals[1:]:
	if x <= b:
	    b = max(b, y)
	else:
	    result.append((a, b))
	    (a, b) = (x, y)
    result.append((a, b))
    return result




More information about the Python-list mailing list