Search code examples
pythongraphnetworkxtriangle-count

Finding total number of triangles using networkx


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?


Solution

  • 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.