Iterate variable for every node | Node Connectivity in Python Graph
Question: I would like to find node connectivity between node 1 and rest of the nodes in
a graph. The input text file format is as follows:

    
    
    1 2 1
    1 35 1
    8 37 1
    

and so on for 167 lines. First column represents source node, second column
represents destination node while the last column represents weight of the
edge.

I'm trying to read the source, destination nodes from input file and forming
an edge between them. I need to then find out if it is a connected network
(only one component of graph and no sub-components). Here is the code

    
    
    from numpy import*
    import networkx as nx
    G=nx.empty_graph()
    
    for row in file('out40.txt'):
        row = row.split()
        src = row[0]
        dest = row[1]
        #print src
        G.add_edge(src, dest)
        print src, dest
    
    for i in range(2, 41):
        if nx.bidirectional_dijkstra(G, 1, i): print "path exists from 1 to ", i
    

manually adding the edges using

    
    
    G.add_edge(1, 2)
    

works but is tedious and not suitable for large input files such as mine. The
if loop condition works when I add edges manually but throws the following
error for the above code:

    
    
    in neighbors_iter
    raise NetworkXError("The node %s is not in the graph."%(n,))
    networkx.exception.NetworkXError: The node 2 is not in the graph.
    

Any help will be much appreciated!


Answer: In your code, you're adding nodes `"1"` and `"2"` et cetera (since reading
from a file is going to give you strings unless you explicitly convert them).

However, you're then trying to refer to nodes `1` and `2`. I'm guessing that
`networkx` does not think that `2 == "2"`.

Try changing this...

    
    
    G.add_edge(src, dest)
    

to this:

    
    
    G.add_edge(int(src), int(dest))
    

