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.
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), []))