Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkX shuffles nodes order

I'm beginner to programming and I'm new here, so hello!

I'm having a problem with nodes order in networkX. This code:

letters = []
G = nx.Graph()
for i in range(nodesNum):
    letter = ascii_lowercase[i]
    letters.append(letter)
    print letters

G.add_nodes_from(letters)
print "G.nodes  = ", (G.nodes())

returns this:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'j']

While I would like to have it in normal (alphabetical) order. Could anyone tell me what am I doing wrong? The order is important to me, as later I'm asking user to tell me where the edges are.

Thanks in advance!

like image 338
dreptak Avatar asked Mar 06 '16 19:03

dreptak


2 Answers

You can sort the nodes on output like this

print "G.nodes  = ", sorted(G.nodes())

or similarly you can sort the edges like

print "G.edges = ", sorted(G.edges())
like image 178
Aric Avatar answered Oct 21 '22 19:10

Aric


Aric's solution would do fine if you want to use this for printing only. However if you are going to use adjacent matrix for calculations and you want consistent matrices in different runs, you should do:

letters = []
G = nx.OrderedGraph()
for i in range(10):
    letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'][i]
    letters.append(letter)
    print (letters)

G.add_nodes_from(letters)
print ("G.nodes  = ", (G.nodes()))

which returns

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
like image 32
ozgeneral Avatar answered Oct 21 '22 21:10

ozgeneral