当前位置: 首页>>代码示例>>Python>>正文


Python UnionFind.find方法代码示例

本文整理汇总了Python中UnionFind.UnionFind.find方法的典型用法代码示例。如果您正苦于以下问题:Python UnionFind.find方法的具体用法?Python UnionFind.find怎么用?Python UnionFind.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在UnionFind.UnionFind的用法示例。


在下文中一共展示了UnionFind.find方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: compute_max_clusters_dist

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
def compute_max_clusters_dist(edges, k):
    edges = sorted(edges)
    clusters = UnionFind()
    for i in range(1, 501):
        clusters.make_set(i)
    ithEdge = 0

    while clusters.number_of_groups != k or len(clusters) != 500:
        clusters.union(edges[ithEdge][1], edges[ithEdge][2])
        ithEdge += 1

    while clusters.find(edges[ithEdge][1]) == clusters.find(edges[ithEdge][2]):
        ithEdge += 1
    return edges[ithEdge][0]
开发者ID:LorenzoBi,项目名称:algorithm_design,代码行数:16,代码来源:clustering.py

示例2: f_equivalence_classes

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
 def f_equivalence_classes(self):
     """Returns a partition of the states into finite-difference equivalence clases, using
     the experimental O(n^2) algorithm."""
     sd = symmetric_difference(self, self)
     self_pairs = [(x, x) for x in self.states]
     fd_equiv_pairs = sd.right_finite_states(self_pairs)
     sets = UnionFind()
     for state in self.states:
         sets.make_set(state)
     for (state1, state2) in fd_equiv_pairs:
         set1, set2 = sets.find(state1), sets.find(state2)
         if set1 != set2:
             sets.union(set1, set2)
     state_classes = sets.as_lists()
     return state_classes
开发者ID:bryanj17,项目名称:python-automata,代码行数:17,代码来源:DFA.py

示例3: kruskal

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
	def kruskal(self):
		Weight = {}
		Trees = []
		UnionSet = UnionFind()
		UnionSet.makeset(self.V())
		for v in self.V():
			edge = self.Adj(v)
			for u in edge:
				uv = u + v
				Weight[uv] = self.Weight(u,v)

		#edges = [(self.Weight(u,v),u,v) for v in self.V() for u in self.Adj(v)].sort()
		edges = [(self.Weight(u,v),v,u) for v in self.V() for u in self.Adj(v)]
		edges.sort()
		for w,u,v in edges:
			if UnionSet.find(u) != UnionSet.find(v):
				Trees.append(u+v)
				UnionSet.union(u,v)
		return Trees	
开发者ID:bookcold,项目名称:Algorithm,代码行数:21,代码来源:MST.py

示例4: max_spacing_k_clustering

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
def max_spacing_k_clustering(G, V, k):
    '''
    Apply a variant of Kruskal's MST algorithm to max-spacing k-clustering problems.
    Return the maximum spacing of k-clustering.
    
    G is a list which represents a graph. 
    Each value of G, G[i], is a tuple (u,v,edge_cost) which represents two vertices of an edge and the cost of that edge.
    V is a list of vertices.
    k is the number of clusters.
    '''
    # use Union-Find data structure to represent clusters
    unionfind=UnionFind()
    
    heap=[] # edges
    for u,v,cost in G:
        heappush(heap,(cost,u,v))
      
    n=len(V) # number of vertices
    i=0
    while i<n-k: # An MST has n-1 edges. Stops early by k-1 steps to produce a k-clustering.
        cost,u,v=heappop(heap) # pop the edge with least cost
             
        # check cycle. No cycles if either vertex has not be added to any cluster or they belong to different clusters.
        if unionfind.find(u) is None or unionfind.find(v) is None or unionfind.find(u)!=unionfind.find(v):
            # add the edge.
            unionfind.union(u,v)
            i+=1
            
#     unionfind.getNumGroups()
    
    # in case that vertices of next edges has been added to the same cluster.
    while True:
        cost,u,v=heappop(heap)
        if unionfind.find(u) is None or unionfind.find(v) is None or unionfind.find(u)!=unionfind.find(v):
            return cost
开发者ID:BurningXFlame,项目名称:SADA_Assignments,代码行数:37,代码来源:clustering.py

示例5: clustering_big

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
def clustering_big():
    rV=[]
    with open('clustering_big.txt') as f:
        s=f.readline()
        bits=int(s.split()[1])
        for line in f:
            s=line.replace(' ','')
            v=int(s,2)
            insort_left(rV,v)
    
    n=len(rV)
    
    # only collect vertices one of which has a distance less than 3 with another one.
    V=set([])
    G=[]

    # The brute-force way definitely runs in O (n^2) time. It's too slow.
    # Consider how many ways you can flip 1 bit in a node: 24.  How many ways can you flip 2 bits: 24*23/2.  
    # All together that's only 300 possibilities to try per node.
    ops=[1]
    for i in xrange(bits-1):
        ops.append(ops[i]<<1)
    
    def flip(b,i):
        'flip the ith bit of b'
        o=ops[i]
        return (b&o^o)|(b&(~o))
    
    u=0
    while u<n:
        x=rV[u]
        # handle the case that duplicates of x exist.
        v=bisect_right(rV,x)
        dups=xrange(u,v)
        for i in dups:
            for j in xrange(i+1,v):
                G.append((i,j))
                V.add(i)
                V.add(j)
        
        for j in xrange(bits):
            # handle the case of flipping 1 bit.
            y=flip(x,j)
            for v in bi_index_range(rV,y):
                for i in dups: # handle duplicates, no need to re-compute.
                    G.append((i,v))
                    V.add(i)
                V.add(v)
            # handle the case of flipping 2 bits. 
            for k in xrange(j+1,bits):
                z=flip(y,k)
                for v in bi_index_range(rV,z):
                    for i in dups: # handle duplicates, no need to re-compute.
                        G.append((i,v))
                        V.add(i)
                    V.add(v)
        
        u+=len(dups) # handle duplicates, no need to re-compute.
              
#     print rV
#     print G

    # compute how many clusters these 2-distance vertices union.
    unionfind=UnionFind()
    for u,v in G:
        # check cycle. No cycles if either vertex has not be added to any cluster or they belong to different clusters.
        if unionfind.find(u) is None or unionfind.find(v) is None or unionfind.find(u)!=unionfind.find(v):
            # add the edge.
            unionfind.union(u,v)
    
    return n-len(V)+unionfind.getNumGroups()
开发者ID:BurningXFlame,项目名称:SADA_Assignments,代码行数:73,代码来源:clustering.py

示例6: __init__

# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import find [as 别名]
class GraphGenerator:
    def __init__(self, nodes, density,
                 graphFilePath, outputFilePath, 
                 leftProb = 1 / 3.0, rightProb = 1 / 3.0):
        self.__nodes = nodes
        self.__density = density
        self.__graphFilePath = graphFilePath
        self.__outputFilePath = outputFilePath
        
        self.__leftProb = leftProb
        self.__crossProb = 1 - leftProb - rightProb
        self.__rightProb = rightProb

        self.__UF = UnionFind(nodes)
        self.__graph = [[] for i in range(nodes)]

    def generateTree(self):
        trees = [i for i in range(self.__nodes)]

        while(len(trees) > 1):
            node1 = node2 = -1

            if(random.random() < 0.005):
                random.shuffle(trees)
            
            choice = random.random()
            if(choice <= self.__leftProb):
                node1 = trees.pop(0)
                node2 = trees.pop(0)

                self.__UF.union(node1, node2)
                
                trees[0:0] = [self.__UF.find(node1)]
            elif(choice <= self.__leftProb + self.__crossProb):
                node1 = trees.pop(0)
                node2 = trees.pop()

                self.__UF.union(node1, node2)

                if(random.random() <= 0.5):
                    trees[0:0] = [self.__UF.find(node1)]
                else:
                    trees.append(self.__UF.find(node1))
            else:
                node1 = trees.pop()
                node2 = trees.pop()

                self.__UF.union(node1, node2)

                trees.append(self.__UF.find(node1))

            weight = random.randint(1, 100)

            if(len(self.__graph[node1]) > 0 and random.random() >= 1.0 / len(self.__graph[node1])):
                rand = random.randint(1, len(self.__graph[node1]) >> 1) - 1
                node1 = self.__graph[node1][rand << 1]

            if(len(self.__graph[node2]) > 0 and random.random() >= 1.0 / len(self.__graph[node2])):
                rand = random.randint(1, len(self.__graph[node2]) >> 1) - 1
                node2 = self.__graph[node2][rand << 1]
            
            self.__graph[node1].extend([node2, weight])
            self.__graph[node2].extend([node1, weight])

    def writeGraph(self, mode = True):
        if(mode):
            outputFile = open(self.__graphFilePath, 'w')
        else:
            outputFile = open(self.__outputFilePath, 'w')
        
        for i in range(self.__nodes):
            outputFile.writelines(str(i) + '\n')
        outputFile.writelines('#\n')
        
        for i in range(self.__nodes):
            for j in range(0, len(self.__graph[i]), 2):
                if(self.__graph[i][j] <= i):
                    continue
                
                outputFile.writelines(str(i) + ' ')
                outputFile.writelines(str(self.__graph[i][j]) + ' ')
                outputFile.writelines(str(self.__graph[i][j + 1]) + '\n')
                
        outputFile.close()

    def generateGraph(self):
        density = self.__density

        mark = [-1] * self.__nodes
        for i in range(self.__nodes):
            if(len(self.__graph[i]) >= 2 * density):
                continue

            count = len(self.__graph[i])
            for j in range(0, len(self.__graph[i]), 2):
                mark[self.__graph[i][j]] = 1

            for j in range(i + 1, self.__nodes):
                if(mark[j] == -1):
                    weight = random.randint(101, 200)
#.........这里部分代码省略.........
开发者ID:notul-atul,项目名称:Fredman-Tarjan-MST,代码行数:103,代码来源:GraphGenerator.py


注:本文中的UnionFind.UnionFind.find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。