所以我正在嘗試撰寫一段代碼,因此它需要一個點串列而不是單個點,并且僅當串列中的所有點都在矩形中時才回傳布林值 True。
例如,
allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) should return True
but allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]) should return False
empty list of points allIn((0,0), (5,5), []) should return False
對于兩個錯誤的回傳,我似乎無法讓回傳與上面的示例相匹配。空串列應該回傳 false。知道我哪里出錯了嗎?
def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
x1 = firstCorner[0]
y1 = firstCorner[1]
x2 = secondCorner[0]
y2 = secondCorner[1]
for i in range(len(pointList)):
p_x = pointList[i][0]
p_y = pointList[i][1]
if not ((p_x >= x1 and p_x < x2) and (p_y >= y1 and p_y < y2)):
return False
return True
print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]))
print(allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]))
print(allIn((0,0), (5,5), []))
uj5u.com熱心網友回復:
為了解決這個問題,您必須將 if 陳述句更改為嵌套在上面的 for 回圈中。否則,該陳述句不會檢查串列中的每一個點,而只會檢查最后一個點。
此外,如果您希望您的第一個示例為真,您必須檢查該點是否小于或等于 secondCorner。
您還可以添加一個 if 陳述句以檢查串列是否為空,以便回傳 false,就像您在最后一個示例中所希望的那樣。
if not(pointList):
return False
for i in range(len(pointList)):
p_x = pointList[i][0]
p_y = pointList[i][1]
if not ((p_x >= x1 and p_x <= x2) and (p_y >= y1 and p_y <= y2)):
return False
return True
uj5u.com熱心網友回復:
兩件事情:
- 您只能
False在回圈內回傳。如果回圈從不運行(如果點串列為空,就是這種情況),您將始終回傳 true。 ((p_x >= x1 and p_x < x2) and (p_y >= y1 and p_y < y2))應該是((p_x >= x1 and p_x <= x2) and (p_y >= y1 and p_y <= y2))(矩形的結束坐標應該是包含的,而不是排除的。)
我建議定義一個函式來確定單個點是否在矩形內,然后重用該函式來檢查所有點是否都在矩形內:
from collections import namedtuple
def point_in_rect(point, rect):
return (rect.first.x <= point.x <= rect.second.x) and (rect.first.y <= point.y <= rect.second.y)
def points_in_rect(points, rect):
return bool(points) and all(point_in_rect(point, rect) for point in points)
Point = namedtuple("Point", "x y")
Rectangle = namedtuple("Rectangle", "first second")
rect = Rectangle(Point(0, 0), Point(5, 5))
print(points_in_rect([Point(1, 1), Point(0, 0), Point(5, 5)], rect)) # True
print(points_in_rect([Point(1, 1), Point(0, 0), Point(5, 6)], rect)) # False
print(points_in_rect([], rect)) # False
uj5u.com熱心網友回復:
只需在串列中添加另一個選項。你也可以在這里使用 numpy,避免 for 回圈。
import numpy as np
def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
# list is empty, return False
if not pointList:
return False
arr = np.array(pointList)
return False not in (arr >= firstCorner) & (arr <= secondCorner)
print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)])) # True
print(allIn((0,0), (5,5), [(1,1), (0,0), (5,6)])) # False
print(allIn((0,0), (5,5), [])) # False
例如對于[(1,1), (0,0), (5,6)],陣列變為:
[[1 1]
[0 0]
[5 6]]
變成:
[[ True True]
[ True True]
[ True False]]
# i.e. 6 is out of bounds, creating 1 False in the array, returning False for the function.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492965.html
標籤:Python python-3.x
