Subhankar Ghosh - 4 months ago 33

Python Question

Graph

I am trying to perform BFS on this graph starting from node 16. But my code is giving erroneous output. Can you please help me out. Thanks.

`visited_nodes = set()`

queue = [16]

pardaught = dict()

exclu = list()

path = set()

for node in queue:

path.add(node)

neighbors = G.neighbors(node)

visited_nodes.add(node)

queue.remove(node)

queue.extend([n for n in neighbors if n not in visited_nodes])

newG = G.subgraph(path)

nx.draw(newG, with_labels=True)

My output is:

Output

Answer

The cause of your problem is that you are removing things from (the start of) queue while looping through it.

```
integer_list = [1,2,3]
next_int = 4
for integer in integer_list:
print integer
integer_list.remove(integer)
integer_list.append(next_int)
next_int += 1
```

Produces output

1

3

5