如何创建交集函数?

2024-09-28 05:27:32 发布

您现在位置: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

问题是这个函数只给出了我想要的一半答案,这是什么 更好的方法来检查是否自交?你知道吗


Tags: andselftrue间隔ifdef物体other
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. 两个间隔相交的。你知道吗
  2. 检查间隔是否为空。你知道吗

我假设您使用的是打开间隔。如果没有,请相应调整代码。你知道吗

构建代码

首先,让我们用一个类来表示区间:

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

完整来源

为了您的方便,我附上了完整的资料来源。你知道吗

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)

相关问题 更多 >

    热门问题