Python 如何创建交集函数?
我在做一个一维的间隔,在这里我必须检查是否自交于另一个物体 以下是我到目前为止的情况:Python 如何创建交集函数?,python,Python,我在做一个一维的间隔,在这里我必须检查是否自交于另一个物体 以下是我到目前为止的情况: 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):
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
问题是这个函数只给出了我想要的一半答案,a是什么
检查自相交是否与其他相交的更好方法?您可能需要这样的方法:
def intersects(self, other):
return (other._lbound < self._lbound < other._rbound or
other._lbound < self._rbound < other._rbound or
self._lbound < other._lbound < self._rbound or
self._lbound < other._rbound < self._rbound)
def相交(自身、其他):
返回(其他._lbound<自身._lbound<其他._lbound或
其他。_lbund<自我。_rbund<其他。_rbund或
自我。_lbound<其他。_lbound<自我。_lbound或
自我。_lbund<其他。_rbund<自我。_rbund)
您当然可以使用不等式实现此谓词。这种方法的缺点是可读性差,出错的可能性高。我建议您将此问题分解为两个子问题:
class Interval(object):
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
空间隔将表示为lhs>=rhs
(从数学角度来看,这也是有意义的)。让我们添加一个谓词,检查间隔是否为空:
def is_empty(self):
return self.lhs >= self.rhs
让我们把注意力转向十字路口。两个区间的交点为区间(可能为空)。可以使用min
和max
计算左右端点,如下所示:
def intersect(self, other):
return Interval(max([self.lhs, other.lhs]), min([self.rhs, other.rhs]))
作为最后一步,让我们添加\uuuu repr\uuuu
,以便能够打印间隔并查看其端点:
def __repr__(self):
return 'Interval(%r, %r)' % (self.lhs, self.rhs)
检查非空交叉口
您尝试执行的操作可以表示为:
a.intersect(b).is_empty()
其中a
和b
是两个Interval
s
全源
为了您的方便,我提供了完整的资料来源
class Interval(object):
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
def is_empty(self):
return self.lhs >= self.rhs
def intersect(self, other):
return Interval(max([self.lhs, other.lhs]), min([self.rhs, other.rhs]))
def __repr__(self):
return 'Interval(%r, %r)' % (self.lhs, self.rhs)
你的集合只包含两个元素,而不是一系列的数字。你如何定义“相交”?重叠一个完全在另一个里面?间隔的两端是打开的还是关闭的?重叠我想我会使用小于/大于。你有四个号码要核对。画一幅真实情况的图画,然后在前两个(或后两个)写下代码不等式就足够了-如果self
s端中的一个位于other
内,那么other
s端中的一个肯定也位于self
内。@GregNavis最后两次检查是看一个范围是否完全位于另一个范围内。说得好,Francisco!使用不等式似乎很简单,我一心想简化代码。另外,我注意到当self
与other
相同时,您的代码不起作用,也就是说,一个区间本身不相交,这显然是错误的。我在回答中提出了另一种方法。