Open In App

Community detection in social networks using brute-force method

Last Updated : 05 Sep, 2020
Like Article

Prerequisite- Python Basics, NetworkX Basics 

We are going to divide the nodes of the graph into two or more communities using the brute force method. The brute force method means we will try every division of nodes into communities and check whether the communities are correctly divided or not. We will use a brute force method for this task.


  1. Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.
  2. Now take two lists as FirstCommunity and SecondCommunity.
  3. Now start putting nodes into communities like put 1st node in FirstCommunity and rest N-1 nodes to SecondCommunity and check its inter and intra edges.
  4. Now we will make combinations using itertools.
  5. Repeat steps 3 and 4 for every combination.
  6. Now check which division is best by taking the ratio of intra/number of inter-community edges.
  7. Now find the value of FirstCommunity and SecondCommunity with maximum ratio and print that value.

Below is the implementation.


import networkx as nx
import itertools
def communities_using_brute(gfg):
  nodes = gfg.nodes()
  n = gfg.number_of_nodes()
  first_community = []
  for i in range(1, n//2 + 1):
    c = [list(a) for a in itertools.combinations(nodes, i)]
  second_community = []
  for i in range(len(first_community)):
    b = list(set(nodes)-set(first_community[i]))
  # Which division is best...
  intra_edges1 = []
  intra_edges2 = []
  inter_edges = []
  # ratio of number of intra/number of inter
  # community edges
  ratio = []  
  for i in range(len(first_community)):
  for i in range(len(second_community)):
  e = gfg.number_of_edges()
  for i in range(len(first_community)):
  # Calculate the Ratio
  for i in range(len(first_community)):
  print('[ ', first_community[mindex], ' ] , [ ', second_community[mindex], ' ]')
# Example graph
gfg=nx.barbell_graph(5, 0)


[ [0,1,2,3,4] ] , [ [8,9,5,6,7] ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads