Visualizing the complement of a graph using networkx
Given a graph G complement of the graph is obtained by removing the edges contained in G from the complete graph having the same number of nodes as G.
Initial Graph G:
The complement of G:
Realizing Complement using Python :
We will use networkx.complement() function for our task
- Returns the complement of the graph object passed.
- The value returned is of the same type of the value passed i.e networkx graph object.
- G is the initial object passed.
- Although the complement is being created but no self-loops and parallel edges are created.
Working of complement(G) function:
An edge (n,n2) where n is iterator used to iterate over G is added to complement graph if following conditions are met:
- n and n2 are not neighbours i.e n2 are in the adjacency list of n and vice versa.
- And n != n2.
- n and n2 both are part of G.
- We will import networkx with an alias nx.
- Create a sample graph object G using path_graph() function.
- We will then call complement function passing G as an argument.
- We will capture the object returned by complement function in another object G_C.
- We will then call draw() function passing G_C as an argument which will display of the complement graph.
By using the complement() method all the edges in G were removed and all other possibilities were added to the complement of G and printed.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.