Search code examples
python-3.xnetworkxgraph-theorybipartite

How to build a bipartite using networkx (python)


Why the result shows the False?

import networkx as nx
P1 = [1, 2, 3]
P2 = ["a", "b", "c"]
PPI = list(zip(P1, P2))
B = nx.Graph()
B.add_nodes_from(P1, bipartite=0)
B.add_nodes_from(P2, bipartite=1)
B.add_edges_from(PPI)
print(nx.is_connected(B))

Solution

  • Because your graph is not connected. When you plot your graph: bipartiteGraph

    you see that you have 3 subgraphs that are not connected (i.e. there is no edge that connects them). But your graph is bipartite:

    print(nx.is_bipartite(B))
    

    Output:

    True
    

    A graph that is connected and bipartite is shown below:

    import networkx as nx
    P1 = [1, 2, 3]
    P2 = ["a", "b", "c"]
    PPI = [(1, 'a'), (2, 'b'), (3, 'c'), (1, 'b'), (2, 'c')]
    B = nx.Graph()
    B.add_nodes_from(P1, bipartite=0)
    B.add_nodes_from(P2, bipartite=1)
    B.add_edges_from(PPI)
    print(nx.is_connected(B))
    print(nx.is_bipartite(B))
    

    Output:

    True
    True