与Python相交的矩形

2024-10-05 10:10:16 发布

您现在位置:Python中文网/ 问答频道 /正文

给定两个矩形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:

^{pr2}$

函数检查矩形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时,它才会失败,但我不知道为什么。在

编辑:

我使用quickcheck for Python和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)

Tags: andrighthelpertruetopdefleftlists
1条回答
网友
1楼 · 发布于 2024-10-05 10:10:16

看看你的第一个版本:

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

假设您完成了所有正确的交集情况,这将返回False,无论{}是否包含{}。在

但在你的第二个版本中:

^{pr2}$

这将返回Falseis r1不包含r2,否则返回{}。在

所以,在“当矩形1包含矩形2”的情况下,它们做了不同的事情。在

作为附带问题:为什么包含r2r1与包含r1的{}返回不同的结果?在

相关问题 更多 >

    热门问题