Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of multiple ranges

Tags:

I have these ranges:

7,10 11,13 11,15 14,20 23,39 

I need to perform a union of the overlapping ranges to give ranges that are not overlapping, so in the example:

7,20 23,39 

I've done this in Ruby where I have pushed the start and end of the range in array and sorted them and then perform union of the overlapping ranges. Any quick way of doing this in Python?

like image 399
bioinf80 Avatar asked Mar 07 '13 14:03

bioinf80


People also ask

What is Union in range?

In VBA Union means joining two or more ranges together. This function is similar to the range function in excel. This is the most common situation in our work when we need to combine one or more ranges with each other. Union function comes very handily in those situations.

How do you select multiple ranges at once?

Just press and hold down the Ctrl key, and you can select multiple non-adjacent cells or ranges with mouse clicking or dragging in active worksheet.

How do you combine ranges in Excel?

Combining same ranges from multiple sheets - 3D formulaIn the leftmost cell of the destination range (A3), start typing the formula: =VSTACK( Click the tab of the first worksheet. While holding the Shift key, click the tab of the last worksheet. Select the range that you want to combine in all of the sheets.

How do I combine ranges in VBA?

In VBA, there is a “MERGE” method that you can use to merge a range of cells or even multiple ranges into one. This method has an argument “Across” which is optional. If you specify TRUE it will merge each row in the range separately, and if you specify FALSE it will merge the entire range as one.


1 Answers

Let's say, (7, 10) and (11, 13) result into (7, 13):

a = [(7, 10), (11, 13), (11, 15), (14, 20), (23, 39)] b = [] for begin,end in sorted(a):     if b and b[-1][1] >= begin - 1:         b[-1] = (b[-1][0], end)     else:         b.append((begin, end)) 

b is now

[(7, 20), (23, 39)] 

EDIT:

As @CentAu correctly notices, [(2,4), (1,6)] would return (1,4) instead of (1,6). Here is the new version with correct handling of this case:

a = [(7, 10), (11, 13), (11, 15), (14, 20), (23, 39)] b = [] for begin,end in sorted(a):     if b and b[-1][1] >= begin - 1:         b[-1][1] = max(b[-1][1], end)     else:         b.append([begin, end]) 
like image 56
eumiro Avatar answered Sep 18 '22 17:09

eumiro