Example #1
0
def spanning_tree(g: Graph) -> {(str, str, int)}:
    answer = set()
    edges = sorted((e[2], e[0], e[1]) for e in g if len(e) != 1)
    components = EquivalenceClass(g.all_nodes())
    n = len(g.all_nodes())
    for v, o, d in edges:
        if n == 1:
            return answer
        if not components.in_same_class(o, d):
            answer.add((o, d, v))
            components.merge_classes_containing(o, d)
            n -= 1
    return answer
def spanning_tree(g : Graph) -> {(str,str,int)}:
    answer = set()
    edges = sorted( (e[2],e[0],e[1]) for e in g if len(e) != 1) 
    components = EquivalenceClass(g.all_nodes())
    n = len(g.all_nodes())
    for v,o,d in edges:
        if n == 1:
            return answer
        if not components.in_same_class(o, d):
            answer.add((o,d,v))
            components.merge_classes_containing(o, d)
            n -= 1
    return answer
Example #3
0
def minimum_spanning_tree(g):
    from priorityqueue import PriorityQueue as PQ
    from equivalence   import EquivalenceClass as EC
    answer = Graph()
    ec = EC(g.nodes())
    # Smaller edge values have higher priority
    for e in PQ(g.edges(),key=(lambda e : g.edge_value(e)),reverse=True):
        if not ec.in_same_class(e[0],e[1]):
            ec.merge_classes_containing(e[0],e[1]) 
            answer.add_edge(e,g.edge_value(e))
        if answer.edge_count() == g.node_count()-1:
            break
    else: return None
    return answer
Example #4
0
def minimum_spanning_tree(g):
    from priorityqueue import PriorityQueue as PQ
    from equivalence import EquivalenceClass as EC
    answer = Graph()
    ec = EC(g.nodes())
    # Smaller edge values have higher priority
    for e in PQ(g.edges(), key=(lambda e: g.edge_value(e)), reverse=True):
        if not ec.in_same_class(e[0], e[1]):
            ec.merge_classes_containing(e[0], e[1])
            answer.add_edge(e, g.edge_value(e))
        if answer.edge_count() == g.node_count() - 1:
            break
    else:
        return None
    return answer
Example #5
0
def connected_components(g):
    from equivalence import EquivalenceClass as EC
    ec = EC(g.nodes())
    for e in g.edges():
        ec.merge_classes_containing(e[0], e[1])
    return ec.all_classes()
Example #6
0
def connected_components(g):
    from equivalence import EquivalenceClass as EC
    ec = EC(g.nodes())
    for e in g.edges():
        ec.merge_classes_containing(e[0],e[1]) 
    return ec.all_classes()
Example #7
0
 def setup(size):
     global ec
     ec = EquivalenceClass([i for i in range(size)])