Find all tuples related to a certain string in Python

前端 未结 3 2000
谎友^
谎友^ 2021-01-15 14:49

I am trying to find all tuples related to a string, not just matched to it. Here is what I made:

from itertools import chain

data = [(\'A\',\'B\'),(\'B\',\'         


        
3条回答
  •  轮回少年
    2021-01-15 15:30

    Your problem is to find the connected component of init in an undirected graph defined by an edge list data structure.

    This data structure is not very convenient to use for this problem, so the first step is to transform it into an adjacency list. From there, we can apply any standard graph traversal algorithm, such as depth first search. Once we're done, we can transform the result back into the edge list format you want for your output.

    from collections import defaultdict
    
    def find_connected_component(edge_list, start):
        # convert to adjacency list
        edges = defaultdict(list)
        for a, b in edge_list:
            edges[a].append(b)
            edges[b].append(a)
    
        # depth-first search
        stack = [start]
        seen = set()
    
        while stack:
            node = stack.pop()
            if node not in seen:
                seen.add(node)
                stack.extend(edges[node])
    
        # convert back to edge list
        return [ edge for edge in edge_list if edge[0] in seen ]
    

    Usage:

    >>> find_connected_component(data, init)
    [('A', 'B'), ('B', 'C'), ('B', 'D'), ('B', 'F'), ('F', 'W'), ('W', 'H')]
    

提交回复
热议问题