3

I want to count the total number of triangles in a graph using networkx python package.

I have tried the following:

import networkx as nx
g = ## some graph
t = nx.triangles(g)

However, nx.triangles() returns a dictionary denoting the number of triangles each vertex belongs to.

I cannot find any direct relationship between the total number of triangles and the values in the dictionary returned. And I could not find a method in networkx that directly returns the total number of nodes as a single integer value.

Is there any relationship between the dictionary mentioned above and the total number of triangles? If not, how can I compute the total number of triangles using networkx?

Ahsan Tarique
  • 581
  • 1
  • 11
  • 22

2 Answers2

3

sum(D.values()) sums up the values in a dictionary. Each triangle is counted as a triangle for each of the three nodes. Thus the sum of the values should be 3 times the number of triangles.

Joel
  • 22,598
  • 6
  • 69
  • 93
3

If G is your network then it's:

number_of_triangles = sum(nx.triangles(G).values()) / 3
Ulf Aslak
  • 7,876
  • 4
  • 34
  • 56