在Python中合并间隔(Merging intervals in Python)

编程入门 行业动态 更新时间:2024-10-28 03:18:07
在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 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.

最满意答案

尝试这个

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

更多推荐

本文发布于:2023-07-26 19:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   Python   intervals   Merging

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!