如何确定给定的 P(x,y) 点是否位于数组的边界内?以下是我的尝试,我无法打印出准确的密钥



如果点在零件边界内,则算法应返回零件号。否则算法应该返回0。

Part n ({Xmin,Ymin},{Xmax,Ymax}).
Xmin (mm) Ymin (mm) Xmax (mm) Ymax (mm)
Part 1 30 700 180 850
Part 2 650 750 750 870
Part 3 50 20 250 120
Part 4 500 500 700 550
# Function that compares the inputs to the database variables.
def FindPart(xmin, ymin, xmax, ymax, x, y, d) :
for k,v in d.items():
if (x >= xmin and x <= xmax and y >= ymin and y <= ymax) :
v = d.values()
# print(v)
return True
else :
return False
# This is the database of parts
party = {"Part1": [30, 700, 180, 850],
"Part2": [650, 750, 750, 870],
"Part3": [50, 20, 250, 120],
"Part4": [500, 500, 700, 550]}
# Input of parts search
x = int(input('Enter a number: '))
y = int(input('Enter a number: '))
d = party
key_list = list(party.keys())
val_list = list(party.values())
# Loop through the parts bin database and compare inputs
# to find the exact bin
for xmin , ymin , xmax , ymax in party.values():
# Function call
if FindPart(xmin, ymin, xmax, ymax, x, y, d):
w = [i for i, e in enumerate(w) if FindPart(xmin, ymin, xmax, ymax, x, y, d)]
print(w)
break
else:
print("0")`

您不需要在字典上循环两次。要么在函数中执行,要么在主代码中执行。尝试:

def withinBoundary(xmin, ymin, xmax, ymax, x, y):
if x in range(xmin, xmax+1) and y in range(ymin, ymax+1):
return True
return False
# Input of parts search
x = int(input('Enter a number: '))
y = int(input('Enter a number: '))
matches = list()
for part, limits in party.items():
if withinBoundary(*limits, x, y):
matches.append(part)
print(matches)

以下是对not_speshal的答案的一个轻微修改:

def within_boundary(xmin, ymin, xmax, ymax, x, y):
if xmin <= x <= xmax and ymin <= y <= ymax:
return True
return
parts = {
"Part1": [30, 700, 180, 850],
"Part2": [650, 750, 750, 870],
"Part3": [50, 20, 250, 120],
"Part4": [500, 500, 700, 550]
}
# Input of parts search
x = int(input('Enter a number: '))
y = int(input('Enter a number: '))
for part_number, limits in enumerate(parts.values(), start=1):
if within_boundary(*limits, x, y):
boundary = part_number
break
else:
boundary = 0

从您的代码和问题来看,您似乎希望标识该点所属的单个区域,而不是区域列表。

如果点在给定区域内,则上述for循环将中断。只有当for循环在所有元素上迭代而不中断时(即,如果点不在任何区域内(,才会执行else块。

编辑-我意识到你想要的是零件号而不是零件名称。我已经更新了for循环以反映这一点。

def within_boundary(xmin, ymin, xmax, ymax, x, y):
if xmin <= x <= xmax and ymin <= y <= ymax:
return True
return
parts = {
"Part1": [30, 700, 180, 850],
"Part2": [650, 750, 750, 870],
"Part3": [50, 20, 250, 120],
"Part4": [500, 500, 700, 550]
}
# Input of parts search
x = 650 #int(input('Enter a number: '))
y = 751 #int(input('Enter a number: '))
for part_number, limits in enumerate(parts.values(), start=1):
if within_boundary(*limits, x, y):
boundary = part_number
break
else:
boundary = 0

print("Part", boundary)

最新更新