简体   繁体   中英

Python Queue.Queue and deque consistency?

Given this code...

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

Where graph is a dictionary representing a directed graph, eg, {'stack':['overflow'], 'foo':['bar']} ie, stack is pointing to overflow and foo is pointing to bar.

Why am I not getting the same result when I replace Queue.Queue with deque from collections to increase efficiency?

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

Your Queue.Queue version uses FIFO while your deque version uses FILO. You should use path = q.popleft() instead to fix this.

Note that Queue.Queue internally uses an underlying deque to represent the queue. For more info, see the relevant documentation (see _get method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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