I came across a BFS code which involves collections and deques but I could not understand it much. I hope some of the pythonistas here can help a n00b out.
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])
Questions:
1) The |= operator seems to be related to bitwise operations – I have no idea how it relates to a BFS, any hints?
2) popleft() should return only one value from what I understand, so how is it returning parent and n here?
3) Is new the series of nodes visited? If I want the nodes, do I just keep appending them to a list?
Thanks in advance.
Craig
a |= bfor sets is the sameas
a = a.union(b).popleft()does indeed returnonly one element, which happens to
be a 2-tuple, and therefore can be
unpacked into two values.
newis the set of not yetvisited nodes.