Andy - 7 months ago 37

Python Question

I use NetworkX to create the following graph.

The graph is created using:

`G = nx.grid_2d_graph(4,3)`

After that two nodes are modified with respect to their positions (just to explain the figure, not necessary for the answer).

Using the following code:

`G.neighbors((1, 1))`

outputs:

`[(0, 1), (1, 2), (1, 0), (2, 1)]`

What I need in addition are the points:

`[(0, 2), (2, 2), (2, 0), (0, 0)]`

This would make up a "loop" around (1, 1) containing all nodes in that "loop". Since I dont't know the correct naming in terms of graphs I have a hard time searching after what I'm looking for.

Answer

I believe that in this specific case would suffice to find which neighbours your neighbours have in common.

the code would be :

```
in_loop = set()
root = (1,1)
for neighb in G.neighbors(root):
others = [n for n in G.neighbors((1,1)) if n != neighb]
for other in others:
if neighb in [x for x in G.neighbors(other) if x != root]:
in_loop.add(neighb)
break
print in_loop
```