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

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

最佳答案

您可能想要这样的东西:

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)

关于python - 如何创建交集函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713781/

相关文章:

python - 使用 redis-py 更改 PubSub 订阅

python - Django ImportError 没有命名的模块

python - 带有 filter_horizo​​ntal 的 Django 管理面板

python - 使用 Python 将 JSON 转换为 CSV(空闲)

java - Python `itertools.chain` 等同于 Java?

python - 无序逃逸——Google Foobar 2020 测试用例不通过

python - 在服务之间传播 JWT token

python - CNTK中的分布式系统使用哪个管道?

python - 如何使用标签提取标签内的文本?

python - 如何从 9 个大小为 N 的数组快速创建 N 个 3x3 矩阵的数组?