Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带集合的Python BFS_Python_Graph_Breadth First Search - Fatal编程技术网

带集合的Python BFS

带集合的Python BFS,python,graph,breadth-first-search,Python,Graph,Breadth First Search,我遇到了一个涉及收集和设计的问题,但我不太明白。我希望这里的一些蟒蛇学者能帮助n00b走出困境 from collections import deque def bfs(g, start): queue, enqueued = deque([(None, start)]), set([start]) while queue: parent, n = queue.popleft() yield parent, n new = se

我遇到了一个涉及收集和设计的问题,但我不太明白。我希望这里的一些蟒蛇学者能帮助n00b走出困境

from collections import deque

def bfs(g, start):
    queue, enqueued = deque([(None, start)]), set([start])
    while queue:
        parent, n = queue.popleft()
        yield parent, n
        new = set(g[n]) - enqueued
        enqueued |= new
        queue.extend([(n, child) for child in new])
问题:

1) |=运算符似乎与逐位运算有关-我不知道它与BFS有什么关系,有什么提示吗

2) 据我所知,popleft()应该只返回一个值,那么它如何返回parent和n呢

3) 新节点是否是访问的一系列节点?如果我想要节点,我是否会一直将它们附加到列表中

提前谢谢

克雷格

  • a |=b
    对于集合是相同的 as
    a=a.union(b)

  • popleft()
    确实返回 只有一个元素,发生在 是2元组,因此可以是 解包成两个值

  • new
    是一组尚未发布的 访问的节点

  • a |=b
    对于集合是相同的 as
    a=a.union(b)

  • popleft()
    确实返回 只有一个元素,发生在 是2元组,因此可以是 解包成两个值

  • new
    是一组尚未发布的 访问的节点

  • (一)

    x |=y
    将x设置为x和y的布尔或<代码>集合覆盖运算符以表示集合并集。基本上,这是一种编写
    enqueue.update(new)
    的奇特方式

    (二)

    队列的第一个元素始终是2元组

    tpl = (a,b)
    x,y = tpl
    
    这是一种奇特的写作方式

    tpl = (a,b)
    assert len(tpl) == 2
    x = tpl[0]
    y = tpl[0]
    
    (三)

    new
    只是新(未访问)节点的临时变量<代码>排队
    包含结果。

    1)

    x |=y
    将x设置为x和y的布尔或<代码>集合覆盖运算符以表示集合并集。基本上,这是一种编写
    enqueue.update(new)
    的奇特方式

    (二)

    队列的第一个元素始终是2元组

    tpl = (a,b)
    x,y = tpl
    
    这是一种奇特的写作方式

    tpl = (a,b)
    assert len(tpl) == 2
    x = tpl[0]
    y = tpl[0]
    
    (三)


    new
    只是新(未访问)节点的临时变量
    enqueued
    包含结果。

    仅回答您的最后一个问题:您的代码片段有一个生成器,这意味着它在首先遍历图形时生成节点。它不做任何实际的搜索,它只是为您遍历节点。使用这段代码的方法是迭代结果,这将依次为您提供所有节点(按广度优先顺序):

    或者,例如,如果需要与特定条件匹配的所有节点的列表:

    nodes = [ node for parent_node, node in bfs(my_graph) if condition(node) ]
    

    回答最后一个问题:这里的代码段有一个生成器,这意味着它在遍历图时会生成节点。它不做任何实际的搜索,它只是为您遍历节点。使用这段代码的方法是迭代结果,这将依次为您提供所有节点(按广度优先顺序):

    或者,例如,如果需要与特定条件匹配的所有节点的列表:

    nodes = [ node for parent_node, node in bfs(my_graph) if condition(node) ]