Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5705

Merging intervals in Python

I am very new to Python programming and have come across a problem statement i have no clue how to solve. I have four lines of input:

0 1
2 4
6 7
3 5

For accepting these 4 lines of input i can do the below:

for i in range(4):
    a,b = list(map(int,input().split(' ')))

I am supposed to merge the intervals into(Output) :

0 1
2 5
6 7

Intervals (2,4) and (3,5) they should be merged into one (2,5).

I am not sure how should i go about this ?

Can someone help me in getting a direction?

Thanks in advance.

Upvotes: 0

Views: 2468

Answers (3)

Guybrush
Guybrush

Reputation: 2780

If you're looking for a Python library that handles intervals arithmetic, consider python-interval. Disclaimer: I'm the maintainer of that library.

(Edited: python-interval was renamed (and greatly improved) to portion, see on GitHub and on PyPI)

import intervals as I

interval = I.empty()
for i, j in [(0, 1), (2, 4), (6, 7), (3, 5)]:
    interval = interval | I.closed(i, j)
print(interval)

results in

[0,1] | [2,5] | [6,7]

See its documentation for more information.

Upvotes: 4

Parth Wavesoul
Parth Wavesoul

Reputation: 1

t=[(0,1),(2,4),(6,7),(3,5)]
t=sorted(t, key=lambda x: x[0])
a=[]
final_list=[]
for i in t[:-1]:
    try:
        if i[1]>=t[t.index(i)+1][0]:
            if i not in a:
                a.append(i)
            a.append(t[t.index(i)+1])
            if t.index(i)==len(t)-2:
                tup = (a[0][0], a[-1][-1])
                final_list.append(tup)
        else:
            tup=(a[0][0], a[-1][-1])
            final_list.append(tup)
            tup=[]
            a=[]
    except:
        final_list.append(i)

if not a:
    tup = (t[-1][0], t[-1][1])
    final_list.append(tup)

print(final_list)

Upvotes: 0

Himaprasoon
Himaprasoon

Reputation: 2659

Try this

from functools import reduce
# inp = [(0,1),(2,9),(6,7),(3,5)]
inp = [(0,1),(2,4),(6,7),(3,5)]
print(inp)
def merge(li,item):
    if li:
        if li[-1][1] >= item[0]:
            li[-1] = li[-1][0], max(li[-1][1],item[1])
            return li
    li.append(item)
    return li
print(reduce(merge, sorted(inp), []))

Upvotes: 1

Related Questions