首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python3中实现呼吸优先搜索(如何将'Set‘转换为'Dictionary’

在Python3中实现呼吸优先搜索(如何将'Set‘转换为'Dictionary’
EN

Stack Overflow用户
提问于 2020-06-03 22:53:18
回答 1查看 29关注 0票数 0

大家好,我开始学习Python了。我使用Dictionary Graph进行呼吸优先搜索的方式是错误的。我得到一个错误,我的代码是

代码语言:javascript
运行
复制
graphs = {
    'a': {'b': 3, 'c': 4, 'd': 7},
    'b': {'c': 1, 'f': 5},
    'c': {'f': 6, 'd': 2},
    'd': {'e': 3, 'g': 6},
    'e': {'g': 3, 'h': 4},
    'f': {'e': 1, 'h': 8},
    'g': {'h': 2},
    'h': {'g': 2}
}

这就是我所尝试的。

代码语言:javascript
运行
复制
def bfs_paths(graphs, start, goal):
    queue = [(start, [start])]
    while queue:
        (vertex, path) = queue.pop(0)
        for next in graphs[vertex] - set(path):
            if next == goal:
                yield path + [next]
            else:
                queue.append((next, path + [next]))
    return queue

def shortest_path(graph, start, goal):
    try:
        return next(bfs_paths(graph, start, goal))
    except StopIteration:
        return None

print(shortest_path(graphs, 'a', 'c'))
EN

回答 1

Stack Overflow用户

发布于 2020-06-03 23:03:01

你的假设确实是正确的

代码语言:javascript
运行
复制
graphs[vertex] - set(path)

字典和集合之间的值无效。Python需要一些默认的(可能是非直观的)行为来使用字典键或值来实现这样的设置差异。相反,尝试将for循环更改为以下内容:

代码语言:javascript
运行
复制
for next in graphs[vertex]:
        if next in set(path):
            continue

这将会达到你想要的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62175920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档