我正在解决在无向图形上计算三角形数量的相同问题,wisty 的解决方案在我的情况下非常有效。我对其进行了一些修改,因此只计算无向三角形。
#### 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)
当然,例如你需要使用字典
#### Test cycles ####
nodes = {}
nodes[0] = [1, 2, 3]
nodes[1] = [0, 2]
nodes[2] = [0, 1, 3]
nodes[3] = [1]
cycles = list(generate_triangles(nodes))
print cycles
使用 Wisty 的代码,找到的三角形将是
[(0, 1, 2), (0, 2, 1), (0, 3, 1), (1, 2, 3)]
将三角形 (0, 1, 2) 和 (0, 2, 1) 视为两个不同的三角形。使用我修改的代码,这些只算作一个三角形。
我将它与一个相对较小的字典一起使用,该字典不到 100 个键,每个键平均有 50 个值。