Python - Determine overlaps of 3 ranges

大城市里の小女人 提交于 2019-12-12 20:26:15

问题


I had a question regarding how I should go about determining overlaps of three ranges in Python without using any existing libraries :

For instance if I have three ranges as (10,20)(15,25)(18,30), how should I go about finding overlaps between them ?

My answer should be (18,19,20)

Any help would be much appreciated. Thanks !


回答1:


The overlap goes from the highest start point to the lowest end point:

ranges = [(10,20), (15,25), (18,30)]
starts, ends = zip(*ranges)
result = range(max(starts), min(ends) + 1)

Test:

>>> print(*result)
18 19 20



回答2:


While WolframH's answer is the best answer for this case, a more general solution for finding overlaps is available, given you don't need to worry about repeated elements, which is to use sets and their intersection operation.

>>> set(range(10, 21)) & set(range(15, 26)) & set(range(18, 31))
{18, 19, 20}

Or, as a more general solution:

ranges = [(10, 20), (15, 25), (18, 30)]
set.intersection(*(set(range(start, finish+1)) for start, finish in ranges))


来源:https://stackoverflow.com/questions/10761833/python-determine-overlaps-of-3-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!