问题
I am trying to find triangles in graph using the following code :
triangles_list = []
for v1 in G.nodes():
v1_nebs = G.neighbors(v1)
if len(v1_nebs)>=2:
for v2 in v1_nebs:
for v3 in v1_nebs:
if v2==v3:
continue
else:
if v2 in G.neighbors(v3):
list_str = []
list_str.append(int(v1))
list_str.append(int(v2))
list_str.append(int(v3))
list_str.sort()
triangles_list.append(list_str)
Is there any optimization that can be done in this code or does networkx has an inbuilt method to find the triangles ?
回答1:
Another way could be to use enumerate_all_cliques and retrieve cliques of size 3, since a triangle is essentially a clique of size 3.
import networkx as nx
G = nx.complete_graph(5)
cliq_list = list(nx.clique.enumerate_all_cliques(g))
traingle_list = [ x for x in cliq_list if len(x)==3 ]
#[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
来源:https://stackoverflow.com/questions/51263510/efficient-way-to-extract-triangles-in-a-graph