【问题标题】:BFS - How to check if an object is in a set of objectsBFS - 如何检查一个对象是否在一组对象中
【发布时间】: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]。它将棋盘添加到已探索集合中,但仍将其添加到队列中......

enter image description here

  • 不要发布数据 - 将文本复制或输入到问题中。请阅读如何提出一个好问题并尝试发布Minimal Reproducible Example,以便我们更好地帮助您。

标签: python-3.x breadth-first-search


【解决方案1】:

您可以为此编写一个单元测试:

import unittest

class BfsTest(unittest.TestCase):

    def test_in(self):
        n = [some constant]
        explored = [some constant]
        self.assertIn(n, explored)
        self.assertTrue(n in explored)

(如果您发现更多信息,或者将其翻转为否定)

有了这些,您就可以更好地处理debug 更大的程序。


看来您可能用可变的list 表示状态 在不可变的str 会更方便的情况下。 编写单元测试以验证您对in 的理解 运算符适用于两种数据类型。


in 运算符在 O(1) 恒定时间内完成 set 容器, 但是对于 list 容器,在 O(n) 线性时间内。 仔细选择您的容器类型。


您可能会发现编写一对小函数很方便 将列表转换为字符串,反之亦然, 也许使用来自json 库的转储/加载。 字符串具有不可变和可散列的优点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多