0

如果该点在零件边界内,则算法应返回零件编号。否则,算法应该返回 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")`
4

3 回答 3

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)
于 2021-12-14T17:46:48.557 回答
0
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)
于 2021-12-14T19:08:10.110 回答
0

这是对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 循环将中断。else只有当 for 循环遍历所有元素而不中断时,才会执行该块 - 即,如果该点不在任何区域内。

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

于 2021-12-14T18:16:30.537 回答