繁体   English   中英

Python Queue.Queue和deque一致性?

[英]Python Queue.Queue and deque consistency?

鉴于此代码......

import Queue

def breadthFirstSearch(graph, start, end):
q = Queue.Queue()
path = [start]
q.put(path)
visited = set([start])
while not q.empty():
    path = q.get()
    last_node = path[-1]
    if last_node == end:
        return path
    for node in graph[last_node]:
        if node not in visited:
            visited.add(node)
            q.put(path + [node])

其中graph是表示有向图的字典,例如{'stack':['overflow'],'foo':['bar']}即,堆栈指向溢出而foo指向bar。

当我将Queue.Queue替换为集合中的deque以提高效率时,为什么我得不到相同的结果?

from collections import deque

def breadthFirstSearch(graph, start, end):
q = deque()
path = [start]
q.append(path)
visited = set([start])
while q:
    path = q.pop()
    last_node = path[-1]
    if last_node == end:
        return path
    for node in graph[last_node]:
        if node not in visited:
            visited.add(node)
            q.append(path + [node])

Queue.Queue版本使用FIFO,而deque版本使用FILO。 您应该使用path = q.popleft()来修复此问题。

请注意, Queue.Queue内部使用底层deque来表示队列。 有关详细信息,请参阅相关文档 (请参阅_get方法)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM