Find all the keys cluster in a list

后端 未结 2 942
轮回少年
轮回少年 2021-01-14 05:25

I have a \"combination\" problem to find a cluster of different keys for which I try to find a optimized solution:

I have this list of list \"l\":

l          


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-14 06:07

    You can see it as the problem of finding the connected components in a graph:

    l = [[1, 5], [5, 7], [4, 9], [7, 9], [50, 90], [100, 200], [90, 100],
         [2, 90], [7, 50], [9, 21], [5, 10], [8, 17], [11, 15], [3, 11]]
    # Make graph-like dict
    graph = {}
    for i1, i2 in l:
        graph.setdefault(i1, set()).add(i2)
        graph.setdefault(i2, set()).add(i1)
    # Find clusters
    clusters = []
    for start, ends in graph.items():
        # If vertex is already in a cluster skip
        if any(start in cluster for cluster in clusters):
            continue
        # Cluster set
        cluster = {start}
        # Process neighbors transitively
        queue = list(ends)
        while queue:
            v = queue.pop()
            # If vertex is new
            if v not in cluster:
                # Add it to cluster and put neighbors in queue
                cluster.add(v)
                queue.extend(graph[v])
        # Save cluster
        clusters.append(cluster)
    print(*clusters)
    # {1, 2, 100, 5, 4, 7, 200, 9, 10, 50, 21, 90} {8, 17} {3, 11, 15}
    

提交回复
热议问题