gpt4 book ai didi

python - 用 Python 相交矩形

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:22 25 4
gpt4 key购买 nike

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

函数一:

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

功能二:

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 时才会失败,但我想不通为什么。

编辑:

我正在使用 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)

最佳答案

看看你的第一个版本:

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

假设你通过了所有正确的交集案例,这将返回 False 无论 r1 是否包含 r2

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

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

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

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com