I am working on the same problem of counting the number of triangles on an undirected graph, and a witty solution works fine in my case. I changed it a bit, so only undirected triangles are taken into account.
#### function for counting undirected cycles def generate_triangles(nodes): visited_ids = set() # mark visited node for node_a_id in nodes: temp_visited = set() # to get undirected triangles for node_b_id in nodes[node_a_id]: if node_b_id == node_a_id: raise ValueError # to prevent self-loops, if your graph allows self-loops then you don't need this condition if node_b_id in visited_ids: continue for node_c_id in nodes[node_b_id]: if node_c_id in visited_ids: continue if node_c_id in temp_visited: continue if node_a_id in nodes[node_c_id]: yield(node_a_id, node_b_id, node_c_id) else: continue temp_visited.add(node_b_id) visited_ids.add(node_a_id)
Of course you need to use a dictionary like
Using the Vista code, the triangles found will be [(0, 1, 2), (0, 2, 1), (0, 3, 1), (1, 2, 3)]
which considered the triangle (0, 1, 2) and (0, 2, 1) to be two different triangles. With a modified code, they are considered only one triangle.
I used this with a relatively small dictionary of less than 100 keys, and each key has an average of 50 values.
Alex Huong Tran
source share