python - 使用 Python 求相交矩形

标签 python math logic conditional-statements intersection

给定两个矩形 r1 和 r2,我尝试测试两者是否相交。 为什么以下两个函数不产生相同的输出?

函数1:

def separate_helper(r1, r2):
  r1_left, r1_top, r1_right, r1_bottom = r1
  r2_left, r2_top, r2_right, r2_bottom = r2

  if r1_right < r2_left:
    separate = True
  elif    r1_left > r2_right:
    separate = True
  elif r1_top > r2_bottom:
    separate = True
  elif r1_bottom < r2_top:
    separate = True
  elif contains(r1, r2):
    separate = False
  else:
    separate = False
  return separate

函数2:

def separate_helper2(r1, r2):
  r1_left, r1_top, r1_right, r1_bottom = r1
  r2_left, r2_top, r2_right, r2_bottom = r2

  separate = r1_right < r2_left or \
    r1_left > r2_right or \
    r1_top > r2_bottom or \
    r1_bottom < r2_top or \
    not contains(r1, r2)
  return separate

检查矩形 1 是否包含矩形 2 的函数:

def contains(r1, r2):
  r1_left, r1_top, r1_right, r1_bottom = r1
  r2_left, r2_top, r2_right, r2_bottom = r2
  return r1_right >= r2_right and  r1_left <= r2_left and  r1_top <= r2_top and  r1_bottom >= r2_bottom

这是一个失败的测试用例:

assert separate_helper([29, 35, 53, 90], [23, 47, 90, 86]) == separate_helper2([29, 35, 53, 90], [23, 47, 90, 86])

只有当矩形 1 包含矩形 2 时才会失败,但我无法理解为什么。

编辑:

我正在使用Python的quickcheck和nose来测试该函数。这是我正在使用的测试代码:

from qc import forall, lists, integers
from intersect import separate_helper, separate_helper2

@forall(tries=100, r1=lists(items=integers(), size=(4, 4)), r2=lists(items=integers(), size=(4, 4)))
def test_separate(r1, r2):
  assert separate_helper(r1, r2) == separate_helper2(r1, r2)

最佳答案

看看你的第一个版本:

elif contains(r1, r2):
  separate = False
else:
  separate = False

假设您完成了所有正确相交的情况,无论 r1 是否包含 r2 都将返回 False

但是在你的第二个版本中:

... or \
not contains(r1, r2)

如果r1不包含r2,则返回False,否则返回True

因此,在“当矩形 1 包含矩形 2 时”的情况下,他们正在做不同的事情。

作为一个附带问题:为什么包含 r2r1 返回的结果与包含 r1r2 不同?

关于python - 使用 Python 求相交矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15889345/

相关文章:

c - 我可以使用什么更准确的算法来计算数字的正弦?

javascript - 如何通过javascript传递长数字?

node.js - 如何杀死node.js中生成的进程

python - 使用 Python 正则表达式在字符之间拆分字符串

python - 使用 matplotlib 的动画子图

python - 如何使用Python dict获得类(class)前10名的学生

python - 如何访问 Django 中的低级 psycopg2 连接?

c++ - 优雅地上下数

c - 关于 "C"中的 Prime Generation - 我的代码有什么问题? -

java - 字符串数组大小和 for 循环访问元素