Search code examples
pythonnetworkxintersection

Find common values in multiple lists and plot a graph too (python+NetwrokX)


I would like to find numbers that exist in all the lists.i'm trying but this code giving me unhashable error. anybody else help me how i can remove this error ?? code and screenshot are given below

   import networkx as nx
    G = nx.karate_club_graph()
    tri=nx.triangles(G) 
    all_cliques= nx.enumerate_all_cliques(G)
    triad_cliques=[x for x in all_cliques if len(x)==3 ]
    print(triad_cliques)
    cliques = nx.find_cliques(G)
    cliques3 = [clq for clq in cliques if 3<=len(clq)<= 3]
    print()
    elements_in_all = list(set.intersection(*map(set, [cliques,triad_cliques])))
    print(elements_in_all)

[Error][1]: https://i.sstatic.net/5Ei0H.png


Solution

  • I think that a set cannot take list for element. So I replaced list of 3 numbers by tuple of 3 numbers. I replaced cliques3 by cliques and inserted cliques to print:

    import networkx as nx
    G = nx.karate_club_graph()
    tri=nx.triangles(G) 
    all_cliques= nx.enumerate_all_cliques(G)
    triad_cliques=[x for x in all_cliques if len(x)==3 ]
    print(triad_cliques)
    cliques = nx.find_cliques(G)
    cliques = [clq for clq in cliques if 3<=len(clq)<= 3] # replaced cliques3 by cliques
    print(cliques) # inserted cliques to print
    # elements_in_all = list(set.intersection(*map(set, [cliques,triad_cliques]))) ## line replaced by the next
    elements_in_all = set([tuple(x) for x in triad_cliques]) & set([tuple(x) for x in cliques])
    print(elements_in_all)
    

    Output: [[0, 1, 2], [0, 1, 3], [0, 1, 7], [0, 1, 13], [0, 1, 17], [0, 1, 19], [0, 1, 21], [0, 2, 3], [0, 2, 7], [0, 2, 8], [0, 2, 13], [0, 3, 7], [0, 3, 12], [0, 3, 13], [0, 4, 6], [0, 4, 10], [0, 5, 6], [0, 5, 10], [1, 2, 3], [1, 2, 7], [1, 2, 13], [1, 3, 7], [1, 3, 13], [2, 3, 7], [2, 3, 13], [2, 8, 32], [5, 6, 16], [8, 30, 32], [8, 30, 33], [8, 32, 33], [14, 32, 33], [15, 32, 33], [18, 32, 33], [20, 32, 33], [22, 32, 33], [23, 27, 33], [23, 29, 32], [23, 29, 33], [23, 32, 33], [24, 25, 31], [26, 29, 33], [28, 31, 33], [29, 32, 33], [30, 32, 33], [31, 32, 33]] [[0, 1, 17], [0, 1, 19], [0, 1, 21], [0, 4, 10], [0, 4, 6], [0, 5, 10], [0, 5, 6], [0, 8, 2], [0, 12, 3], [2, 32, 8], [5, 16, 6], [33, 32, 14], [33, 32, 15], [33, 32, 18], [33, 32, 20], [33, 32, 22], [33, 32, 31], [33, 26, 29], [33, 27, 23], [33, 28, 31], [24, 25, 31]] {(0, 5, 10), (0, 1, 19), (0, 5, 6), (0, 4, 10), (24, 25, 31), (0, 4, 6), (0, 1, 21), (0, 1, 17)}