0

Whenever I apply H.neighbors(), to any node from my graph it shows none.

import networkx as nx
graph={'A': ['B', 'C'],
       'B': ['C', 'D'],
       'C': ['D','A'],
       'D': ['C'],
       'E': ['F'],
       'F': ['C']}
G = nx.Graph(graph)
H = G.to_directed(graph)
H = nx.DiGraph(graph)
all_adjacent_cells = ['All Adjacent Cells']
backward_cells = ['All Input Cells']
forward_cells = ['All Output Cells']
print(all_adjacent_cells.append(G.neighbors('B')))
print((backward_cells.append(H.neighbors('B'))))

Whenever I apply H.neighbors('B'), put any node from my graph it shows none. But the output should be

backward_cells = 2
forward_cells = 1

How can i get the numbers of neighbor input connected net and output connected net?

Dominique Fortin
  • 2,212
  • 15
  • 20
Aditi Sen
  • 1
  • 1

1 Answers1

2

The None that your code is printing out is not the neighbors of 'B'.

It comes from print(all_adjacent_cells.append(G.neighbors('B'))). What does this command do? G.neighbors('B') is a specific type of object (at the moment it's not important what that type is). It takes that object and appends it to all_adjacent_cells, which is a list, that happens to have the string 'All Adjacent Cells' as its first element (aside, I generally don't think it's a good idea to have lists where some elements mean something completely different from the other elements).

Now what is the returned value of the function append? If I set x = L.append(5), that assignment doesn't really mean what you think it means. L.append(5) modifies L. It appends 5 to it. L itself is modified. So what is x? It's whatever append returns, which is not the same thing as what append modifies. More precisely, append returns None. And that returned value is what your print statement is printing.

Try this:

L=[1,2,3]
x = L.append(4)
print(L)
> [1, 2, 3, 4]
print(x)
> None

Now how to do what you want to do? The object G.neighbors('B') is a type of iterator. For your purposes, I recommend converting it into a list list(G.neighbors('B')) This is something you can print, and it will give the result you want

print(list(G.neighbors('B')))
> ['A', 'C', 'D']
Joel
  • 22,598
  • 6
  • 69
  • 93
  • Thank you so much , i actually needed the numbers of input connected net of 'B' like for this graph for 'B' the input connected net is 'C' and 'D' 'B': ['C', 'D'], as you can see in this line .So for B they will give me 2 as output as there are two elements over there – Aditi Sen Aug 04 '21 at 13:48
  • `H.successors('B')` gives the nodes that `B` links to (`H.neighbors('B')` also gives this). `H.predecessors('B')` gives the nodes that link to `B`. – Joel Aug 04 '21 at 19:53