0

Below is the example for reference:

pairlist = [("A","B"),("Q","R"),("S","T"),("C","E"),("F","G"),("G","I"),("A","Y"),("B","C"),("B","D")]

I need to get the more interconnected values (directly or Indirectly) of tuples from this list

for Example: Refer below list where "A" is linked with "B" in tuple("A","B") in the pairlist[0] position, and "B" is linked with "C" in pairlist[7] and so on it is interconnected indirectly in large number, where as "G" is less interconnected.

pairs1 = ["A", "B", "C", "D", "E", "Y"] #More Interconnected indirectly

pairs2 = ["G", "F", "I"] #Less Interconnected indirectly

The below tuples in the list No where Interconnected with any one.

("Q","R"),("S","T")

Even though "G" is repetitive and it is not interconnected with major once, it seperately interconnected with other elements which is very less connections with others.

How to get the list as below

pairs = ["A", "B", "C", "D", "E", "Y"]
Ondrej K.
  • 8,841
  • 11
  • 24
  • 39

1 Answers1

3

You can use the package networkx:

import networkx as nx

pairlist = [("A","B"),("C","E"),("F","G"),("G","I"),("A","Y"),("B","C"),("B","D")]

G = nx.Graph()
G.add_edges_from(pairlist)
for i in nx.connected_components(G):
    print(i)
# {'B', 'C', 'E', 'D', 'Y', 'A'}
# {'I', 'F', 'G'}

Graph

To draw the graph use:

import matplotlib.pyplot as plt

nx.draw(G, with_labels=True)
plt.show()

or if you use jupyter notebook:

%matplotlib inline
nx.draw(G, with_labels=True)
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73