Python Queue.Queue和deque一致性?

时间:2013-05-25 09:08:12

标签: python queue

鉴于此代码......

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])

1 个答案:

答案 0 :(得分:2)

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

请注意,Queue.Queue在内部使用基础deque来表示队列。有关详细信息,请参阅relevant documentation(请参阅_get方法)