This question already has answers here:
Union of multiple ranges
(5个答案)
7个月前关闭。
我在列表中有如下范围:
ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
我想找到可以从中构造的最长距离(当它们彼此重叠时)。
预期产量:
[(1, 70), (75, 92)]
我有一个解决方案,但是它太复杂了,我相信必须有一个更简单的解决方案来解决这个问题
我的解决方案:
def overlap(x, y):
return range(max(x[0], y[0]), min(x[-1], y[-1]) + 1)
ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
beg, end = min([x[0] for x in ranges]), 0
for i in ranges:
if i[0] == beg:
end = i[1]
while beg:
for _ in ranges:
for i in ranges:
if i[1] > end and overlap(i, [beg, end]):
end = i[1]
print(beg, end)
try:
beg = min([x[0] for x in ranges if x[0] > end])
for i in ranges:
if i[0] == beg:
end = i[1]
except ValueError:
beg = None
输出:
1 70
75 92
python大神给出的解决方案
我认为您可以按范围的开头对输入进行排序,然后遍历它们。在每个项目上,它要么添加到当前范围(如果开始小于当前范围的结束),要么我们得出当前范围并开始累积一个新范围:
def overlaps(ranges):
ranges = sorted(ranges) # If our inputs are garunteed sorted, we can skip this
it = iter(ranges)
try:
curr_start, curr_stop = next(it)
# overlaps = False # If we want to exclude output ranges not produced by overlapping input ranges
except StopIteration:
return
for start, stop in it:
if curr_start <= start <= curr_stop: # Assumes intervals are closed
curr_stop = max(curr_stop, stop)
# overlaps = True
else:
# if overlaps:
yield curr_start, curr_stop
curr_start, curr_stop = start, stop
# overlaps = False
# if overlaps:
yield curr_start, curr_stop
print(list(overlaps([(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)])))
# [(1, 70), (75, 92)]
print(list(overlaps([(20, 30), (5, 10), (1, 7), (12, 21)])))
# [(1, 10), (12, 30)]
从文件中读取用户名和密码[重复] - pythonThis question already has answers here: How to read a file line-by-line into a list? (28个答案) 2年前关闭。 如何在Python中逐行读取文本(例如用户名和密码)?例如,我可以在shell / bash中实现此目的:#!/bin/bash AUTH='/aut…
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
子条件的python条件覆盖 - python我试图找到一个python代码覆盖率工具,该工具可以衡量语句中是否包含子表达式:例如,我想看看下面的示例是否涵盖了condition1 / condition2 / condtion3?if condition1 or condition2 or condition3: x = true_value python大神给出的解决方案 对此的唯一合理答案是:当前…
USB设备发行 - python我目前正在使用PyUSB。由于我不熟悉USB,所以我不知道如何执行以下操作。我已经从Python PyUSB成功连接到我的USB设备硬件。在代码中,我需要重置USB设备硬件。通过向硬件发送命令来完成。现在,在硬件重置后,我想从Python PyUSB释放当前的USB设备。然后,我想在重置后将其重新连接到USB设备硬件。请让我知道,如何释放USB设备连接和接口…