如何创建交叉函数?

时间:2017-05-01 03:12:07

标签: 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):
    """
    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

问题是这个函数只给出了我想要的答案的一半,是什么意思 更好的方法来检查自我是否与其他人相交?

2 个答案:

答案 0 :(得分:2)

你可能想要这样的东西:

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)

答案 1 :(得分:1)

你当然可以用不等式来实现这个谓词。这种方法的缺点是可读性差,很有可能犯错误。我建议你将这个问题分解为两个子问题:

  1. 相交两个区间。
  2. 检查间隔是否为空。
  3. 我假设您正在使用打开间隔。如果没有,请相应调整代码。

    构造代码

    首先,让我们有一个表示间隔的类:

    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
    

    让我们把注意力转向十字路口。两个间隔的交集是间隔(可能是空的)。可以使用minmax计算左右端点,如下所示:

        def intersect(self, other):
            return Interval(max([self.lhs, other.lhs]), min([self.rhs, other.rhs]))
    

    最后一步,让我们添加__repr__,以便我们能够print间隔并查看其终点:

        def __repr__(self):
            return 'Interval(%r, %r)' % (self.lhs, self.rhs)
    

    检查非空交叉点

    您尝试执行的操作可表示为:

    a.intersect(b).is_empty()
    

    其中ab是两个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)