Skip to content Skip to sidebar Skip to footer

How To Join Integers Intervals In Python?

I have used the module intervals (http://pyinterval.readthedocs.io/en/latest/index.html) And created an interval from a set or start, end tuples: intervals = interval.interval([1,8

Solution 1:

The intervals module pyinterval is used for real numbers, not for integers. If you want to use objects, you can create an integer interval class or you can also code a program to join integer intervals using the interval module:

defjoin_int_intervlas(int1, int2):
    ifint(int1[-1][-1])+1 >= int(int2[-1][0]):
        return interval.interval([int1[-1][0], int2[-1][-1]])
    else:
        return interval.interval()

Solution 2:

I believe you can use pyintervals for integer intervals too by adding interval([-0.5, 0.5]). With your example you get

In[40]:  interval([1,8], [9,10], [11,20]) + interval([-0.5, 0.5])
Out[40]: interval([0.5, 20.5])

Solution 3:

This takes a list of tuples like l = [(25,24), (17,18), (5,9), (24,16), (10,13), (15,19), (22,25)]

# Idea by Ben Voigt in https://stackoverflow.com/questions/32869247/a-container-for-integer-intervals-such-as-rangeset-for-cdefsort_condense(ivs):
    iflen(ivs) == 0:
        return []
    iflen(ivs) == 1:
        if ivs[0][0] > ivs[0][1]:
            return [(ivs[0][1], ivs[0][0])]
        else:
            return ivs
    eps = []
    for iv in ivs:
        ivl = min(iv)
        ivr = max(iv)
        eps.append((ivl, False))
        eps.append((ivr, True))
    eps.sort()
    ret = []
    level = 0
    i = 0while i < len(eps)-1:
        ifnot eps[i][1]:
            level = level+1if level == 1:
                left = eps[i][0]
        else:
            if level == 1:
                ifnot eps[i+1][1]
                   and eps[i+1][0] == eps[i][0]+1:
                    i = i+2continue
                right = eps[i][0]
                ret.append((left, right))
            level = level-1
        i = i+1
    ret.append((left, eps[len(eps)-1][0]))
    return ret

In [1]: sort_condense(l)
Out[1]: [(5, 13), (15, 25)]

The idea is outlined in Ben Voigt's answer to A container for integer intervals, such as RangeSet, for C++

Python is not my main language, sorry.

Solution 4:

I came up with the following program:

ls = [[1,8], [7,10], [15,20]]
ls2 = []
prevList = ls[0]
for lists in ls[1:]:
    if lists[0] <= prevList[1]+1:
        prevList = [prevList[0], lists[1]]
    else:
        ls2.append(prevList)
        prevList = lists
ls2.append(prevList)

print ls2 # prints [[1, 10], [15, 20]]

It permutes through all lists and checks if the firsy element of each list is less than or equal to the previous element + 1. If so, it clubs the two.

Post a Comment for "How To Join Integers Intervals In Python?"