我正在做一个一维的间隔,在这里我必须检查是否自交另一个物体。你知道吗
到目前为止,我掌握的情况如下:
def __init__(self, lbound, rbound):
"""
Constructs a new interval given its lower and upper bounds.
"""
self._lbound = lbound
self._rbound = rbound
这是我的职责:
def intersects(self, other):
"""
Returns True if self intersects other and False othewise.
"""
s1 = set([self._lbound, self._rbound])
s2 = set([other._lbound, other._rbound])
if s1.intersection(s2) and s2.intersection(s1):
return True
问题是这个函数只给出了我想要的一半答案,这是什么 更好的方法来检查是否自交?你知道吗
你可能想要这样的东西:
你当然可以用不等式来实现这个谓词。这种方法的缺点是可读性差,出错的可能性很高。我建议您将此问题分解为两个子问题:
我假设您使用的是打开间隔。如果没有,请相应调整代码。你知道吗
构建代码
首先,让我们用一个类来表示区间:
空间隔将用
lhs >= rhs
表示(从数学角度来看,这也是有意义的)。让我们添加一个谓词来检查间隔是否为空:让我们把注意力转向十字路口。两个区间的交点就是一个区间(可能是空的)。可以使用
min
和max
计算左右端点,如下所示:最后一步,让我们添加
__repr__
,以便能够print
间隔并查看其端点:检查非空交叉口
您尝试执行的操作可以表示为:
其中
a
和b
是两个Interval
完整来源
为了您的方便,我附上了完整的资料来源。你知道吗
相关问题 更多 >
编程相关推荐