Efficient way to extract triangles in a graph [duplicate]

纵饮孤独 提交于 2020-08-20 11:50:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!