【发布时间】:2022-10-01 07:25:29
【问题描述】:
我在 for 循环下的 if 语句有问题。我正在检查一个邻居(对象)是否在一个集合中,称为探索(对象集)。由于某种原因,当邻居已经存在于探索中时,它被添加到队列中。如果它已经存在于探索中,我不希望它添加到队列中。有没有更好的方法来检查一个对象是否存在于集合中?
def bfs_search(initial_state):
\"\"\"BFS search\"\"\"
frontier = deque()
initial_state.parent = list(initial_state.config)
frontier.append(initial_state)
explored = set()
while frontier:
state = frontier.pop()
initial_state = state
print(f\"Board State to make children: {initial_state}\")
explored.add(initial_state)
print(f\"is initial state not in explored?: {initial_state not in explored}\")
if test_goal(initial_state):
return initial_state
initial_state.expand()
neighbors = initial_state.children
print(f\"print new neighbors:\", neighbors)
for n in neighbors:
if n not in explored:
time.sleep(1)
frontier.appendleft(n)
return False
输出: 当我进入棋盘[1,2,5,3,4,0,6,7,8]。它将棋盘添加到已探索集合中,但仍将其添加到队列中......
-
不要发布数据 - 将文本复制或输入到问题中。请阅读如何提出一个好问题并尝试发布Minimal Reproducible Example,以便我们更好地帮助您。
标签: python-3.x breadth-first-search