Python: 检查是否所有点都在一个矩形内

Python: check if all points within a rectangle

我写了下面的函数来检查点列表是否在一个矩形内,它应该 return 只有当列表中的所有点都在矩形内时它才应该是真的。

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
    if len(pointList) == 0:
        return False
    for i in range(0, len(pointList)):
        if (secondCorner[0]>=pointList[i][0]>=firstCorner[0] and secondCorner[1]>=pointList[i][1]>=firstCorner[1]):
            return True
        elif (secondCorner[0]>=pointList[i][0]>=firstCorner[0] and firstCorner[1]>=pointList[i][1]>=secondCorner[1]):
            return True
        elif (firstCorner[0]>=pointList[i][0]>=secondCorner[0] and secondCorner[1]>=pointList[i][1]>=firstCorner[1]):
            return True
        elif (firstCorner[0]>=pointList[i][0]>=secondCorner[0] and firstCorner[1]>=pointList[i][1]>=secondCorner[1]):
            return True
    return False

firstCorner和secondCorner的坐标只是定义矩形的一个角,并不一定代表矩形的左上角和右下角。

但是,返回的结果始终为 True。只有当不在矩形中的坐标是列表中的第一个元素时,它才会 return False。

例如:firstCorner = (0,0), secondCorner = (5,5), pointList=[(1,1), (0,0), (5,6)](其中(1, 1) 和 (0,0) 在矩形中,而 (5,6) 不在)

print(allIn((0,0), (5,5), [(1,1), (0,0), (5,6)])) 总是 returns True ,打印结果相同(allIn((0,0),(5,5),[(1,1),(5,6),(0,0)]))。当我将列表作为 print(allIn((0,0), (5,5), [(5,6), (1,1), (0,0)] 时,它只有 returns False ))

谁能帮我看看哪里错了?

您似乎在“for”语句中输入了“return False”?(在下面的代码中放置 1?)

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
    if len(pointList) == 0:
        return False
    for i in range(0, len(pointList)):
        if xx
            return True
        elif xx
            return True
        elif xx
            return True
        elif xx
            return True
        return False  # place 1,here ? cause what you say 
    return False  # or here ? 

另外,如果真正的代码和你问题中的一样,也是错误的, 因为代码实现了“或”逻辑,即如果矩形中存在任何一个点,它将 return True 。 这是我的代码:

def allIn(firstCorner=(0, 0), secondCorner=(0, 0), pointList=[]):
    ret=[]
    if len(pointList) == 0:
        return False
    for i in range(0, len(pointList)):
        if (secondCorner[0] >= pointList[i][0] >= firstCorner[0] and secondCorner[1] >= pointList[i][1] >= firstCorner[
            1]):
            ret.append(1)
        elif (secondCorner[0] >= pointList[i][0] >= firstCorner[0] and firstCorner[1] >= pointList[i][1] >=
              secondCorner[1]):
            ret.append(1)
        elif (firstCorner[0] >= pointList[i][0] >= secondCorner[0] and secondCorner[1] >= pointList[i][1] >=
              firstCorner[1]):
            ret.append(1)
        elif (firstCorner[0] >= pointList[i][0] >= secondCorner[0] and firstCorner[1] >= pointList[i][1] >=
              secondCorner[1]):
            ret.append(1)
        else:
            ret.append(0)

    print("ret:",ret)
    return all(ret)