python - Write a Graph into a file in an adjacency list form [mentioning all neighbors of each node in each line] -


i need write graph in text file each line of file composed 1 node followed neighbors. it's adjacency list is, , function write_adjlist supposed do. unfortunatly it's not case, edge not replicated. in exemple of wikipedia adjacency list :

a adjacent b, c

b adjacent a, c

c adjacent a, b

we can see edges present 2 times (the edge (a,b) in lines 1 , 2, edge (b,c) in lines 2 , 3...).

but if use following code generate small world network :

import networkx nx  n=5  #number of nodes v=2  #number of neighbours p=.1 #rewiring proba  g = nx.connected_watts_strogatz_graph(n,v,p) nx.write_adjlist(g.to_undirected(),"test.txt") 

it gives me :

#adj.py # gmt thu jan 21 06:57:29 2016 # watts_strogatz_graph(5,2,0.1) 0 1 4 1 2 2 3 3 4 4 

where have

0 1 4 1 2 0 2 3 1 3 2 4  4 0 3 

do know how have output want?

actually how write_adjlist defined in order have file written want simple work around can done following function:

def adj_list_to_file(g,file_name):     f = open('tst.txt', "w")     n in g.nodes():         f.write(str(n) + ' ')         neighbor in g.neighbors(n):             f.write(str(neighbor) + ' ')         f.write('\n')  n=5  #number of nodes v=2  #number of neighbours p=.1 #rewiring proba g = nx.connected_watts_strogatz_graph(n,v,p) nx.draw(g, with_labels= true) plt.show() adj_list_to_file(g.to_undirected(),"tst.txt") 

the file output is:

0 1 4  1 0 2  2 1 3  3 2 4  4 0 3  

Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -