这是一个类似于What's the most efficient way to test two integer ranges for overlap?但更高级的问题:
让我们得到两个包含整数范围x1:x2和y1: y2,其中x1 x2和y1≤y2。
x1和/或y1可以是整数或负无穷大(表示为None Python对象),x2和/或y2可以是整数或正无穷大(表示为None Python对象)。
测试这两个范围是否有重叠的最佳方法是什么?
我确信我可以写一个算法,但也许你会为我找到一个更短的Python代码?
(事实上,我处理的不是整数,而是像"3.7“这样的版本字符串。但我想我自己从整型字符串转移到版本字符串是没有问题的。)
发布于 2018-07-26 03:36:00
我认为这应该是可行的,只要检查x1, x2, y1, y2之间可能存在的不同关系即可。这可能可以用更短的形式来编写,但这段代码强调了不同的情况。
def checkIntersection(x1, x2, y1, y2):
if x1 is not None:
if y1 is not None:
if x1 <= y1 and (x2 is None or x2 > y1):
return True
elif y1 <= x1 and (y2 is none or y2 > x1):
return True
else:
return False
else:
if y1 is None:
return True
else:
if x2 is None or x2 > y1:
return True
return False和一个更优雅的解决方案-
import numpy as np
def checkIntersection(x1, x2, y1, y2):
x1 = x1 if x1 is not None else -np.inf
y1 = y1 if y1 is not None else -np.inf
x2 = x2 if x2 is not None else np.inf
y2 = y2 if y2 is not None else np.inf
return (x1 <= y1 and x2 >= y1) or (y1 <= x1 and y2 >= x1)https://stackoverflow.com/questions/51526282
复制相似问题