在Python中合并间隔(Merging intervals in Python)
我是Python编程的新手,遇到了一个问题陈述,我不知道如何解决。 我有四行输入:
0 1 2 4 6 7 3 5为了接受这4行输入,我可以执行以下操作:
for i in range(4): a,b = list(map(int,input().split(' ')))我应该将间隔合并到(输出):
0 1 2 5 6 7间隔(2,4)和(3,5)它们应合并为一(2,5)。
我不知道该怎么办呢?
有人可以帮我指点方向吗?
提前致谢。
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 5For 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 7Intervals (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.
最满意答案
尝试这个
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), []))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), []))更多推荐
发布评论