0

I am facing issue with lists here. It shows unhashable type: 'list' when i run the code

import networkx as nx
import itertools as it

def brute_communities(G):
    nodes = G.nodes()
    n = G.number_of_nodes()

    first_community = []
    for i in range(1, int(n/2 + 1)):
        comb = [list(x) for x in it.combinations(nodes, i)]
        first_community.extend(comb) 

    second_community = []
    for i in range(len(first_community)):
        l = list(set(nodes) - set(first_community))
        second_community.append(l)

    # which division is the best?
    num_intra_edges1 = []
    num_intra_edges2 = []
    num_inter_edges = []
    ratio = [] #ratio is number of intra/number of inter community edges
    for i in range(len(first_community)):
        num_intra_edges1.append(G.subgraph(first_community[i]).number_of_edges())
    
    for i in range(len(second_community)):
        num_intra_edges2.append(G.subgraph(second_community[i]).number_of_edges())
    
    e = G.number_of_edges()

    for i in range(len(first_community)):
        num_inter_edges.append(e - num_intra_edges1[i] - num_intra_edges2[i])

    # Find the ratio
    for i in range(len(first_community)):
        ratio.append((float)(num_intra_edges1[i] + num_intra_edges2[i])/2)
    max_value = max(ratio)
    max_index = ratio.index(max_value)
    print('(', first_community[max_index], '),(', second_community[max_index], ')')

G = nx.barbell_graph(5,0)
brute_communities(G)

I tried converting the two lists 'nodes' and 'first_community' to sets so that i could subtract the values easily and convert the result back to list but I am getting the error as 'unhashable type'

  • 2
    So it wants a hashable type. Have you tried tuples? See more about hashable types [here](https://stackoverflow.com/q/14535730/6394617)? – Joe Aug 21 '23 at 12:03
  • 1
    Also, instead of using code that looks like `for i in range(len(your_iterable)): f(your_iterable[i])`, you might want to try using `for x in your_iterable: f(x)`. You might also want to look into `zip` and `enumerate`. Try [here](https://stackoverflow.com/a/32930263/6394617) – Joe Aug 21 '23 at 13:12

0 Answers0