How to determine the in-degree and out-degree of a node from a graph?

664 Views Asked by At

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?

1

There are 1 best solutions below

2
Joel On

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