Finding cycle of 3 nodes ( or triangles) in a graph

后端 未结 11 2197
南旧
南旧 2020-12-31 15:42

I am working with complex networks. I want to find group of nodes which forms a cycle of 3 nodes (or triangles) in a given graph. As my graph contains about million edges, u

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 16:33

    If you don't care about multiple copies of the same triangle in different order then a list of 3-tuples works:

    from itertools import combinations as combos
    [(n,nbr,nbr2) for n in G for nbr, nbr2 in combos(G[n],2) if nbr in G[nbr2]]
    

    The logic here is to check each pair of neighbors of every node to see if they are connected. G[n] is a fast way to iterate over or look up neighbors.

    If you want to get rid of reorderings, turn each triple into a frozenset and make a set of the frozensets:

    set(frozenset([n,nbr,nbr2]) for n in G for nbr, nbr2 in combos(G[n]) if nbr in G[nbr2])
    

    If you don't like frozenset and want a list of sets then:

    triple_iter = ((n, nbr, nbr2) for n in G for nbr, nbr2 in combos(G[n],2) if nbr in G[nbr2])
    triangles = set(frozenset(tri) for tri in triple_iter)
    nice_triangles = [set(tri) for tri in triangles]
    

提交回复
热议问题