Find all tuples related to a certain string in Python

前端 未结 3 1974
谎友^
谎友^ 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:09

    For more efficient, you might use DSU. This solution works O(N)

    from functools import reduce
    import random
    
    parent = dict()
    init = 'A'
    data = [('A','B'),('B','C'),('B','D'),('B','F'),('F','W'),('W','H'),('G','Z')]
    
    def make_set(v):
        parent[v] = v
    
    def find_set(v):
        if v == parent[v]:
            return v
        parent[v] = find_set(parent[v])
        return parent[v]
    
    def union_sets(a, b):
        a, b = map(find_set, [a, b])
        if a != b:
            if random.randint(0, 1):
                a, b = b, a
            parent[b] = a;
    
    elements = set(reduce(lambda x, y: x+y, data))
    
    for v in elements:
        parent[v] = v
    
    for u, v in data:
        union_sets(u, v)
    
    init_set = find_set(init)
    edges_in_answer = [e for e in data if find_set(e[0]) == init_set]
    print(edges_in_answer)
    

    Output: [('A', 'B'), ('B', 'C'), ('B', 'D'), ('B', 'F'), ('F', 'W'), ('W', 'H')]

提交回复
热议问题