本文整理汇总了Python中UnionFind.UnionFind.union方法的典型用法代码示例。如果您正苦于以下问题:Python UnionFind.union方法的具体用法?Python UnionFind.union怎么用?Python UnionFind.union使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UnionFind.UnionFind
的用法示例。
在下文中一共展示了UnionFind.union方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connectedComponentOutsidePermittedRegionBlacken
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def connectedComponentOutsidePermittedRegionBlacken(img, vstart, vend):
labels = UnionFind()
# pass 1
labeled = set()
for currentPoint in iterImg(img):
y,x = currentPoint
if sum(img[y,x]) <= 100: # black
continue
labeled.add(currentPoint)
neighbors = getSurrounding1(img, y, x)
# if all 4 neighbors are black or unlabeled (ie, 0 labeled white neighbors), assign new label
# if only 1 neighbor is white, assign its label to current point
# if more than 1 of the neighbors are white, assign one of their labels to the current point, and note equivalence
labeled_white_neighbors = [neighbor for neighbor in neighbors if sum(img[neighbor]) > 100 and neighbor in labeled]
if len(labeled_white_neighbors) == 0: # assign new label
z = labels[currentPoint]
else:
for neighbor in labeled_white_neighbors:
labels.union(neighbor, currentPoint)
# now blacklist all sets st they have a child that is in the forbidden region
blacklist = set()
for currentPoint in labeled:
y,x = currentPoint
if y < vstart or y > vend:
blacklist.add(labels[currentPoint])
# pass 2 - blacken blacklisted components
for currentPoint in labeled:
y,x = currentPoint
curset = labels[currentPoint]
if curset in blacklist:
img[y,x] = (0,0,0)
示例2: max_spacing_k_clustering
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [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
示例3: MinimumSpanningTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def MinimumSpanningTree(graph, weights):
"""
Return the minimum spanning tree of an undirected graph G.
G should be represented in such a way that iter(G) lists its
vertices, iter(G[u]) lists the neighbors of u, G[u][v] gives the
length of edge u,v, and G[u][v] should always equal G[v][u].
The tree is returned as a list of edges.
"""
if not isinstance(graph, UndirectedGraph):
raise ValueError("Provided graph is not an UndirectedGraph.")
for vertex in range(graph.n_vertices):
for child in graph.adjacency_list[vertex]:
if weights[vertex, child] != weights[child, vertex]:
raise ValueError("Assymetric weights provided.")
# Kruskal's algorithm: sort edges by weight, and add them one at a time.
# We use Kruskal's algorithm, first because it is very simple to
# implement once UnionFind exists, and second, because the only slow
# part (the sort) is sped up by being built in to Python.
subtrees = UnionFind()
tree = []
for W, u, v in sorted((weights[u][v], u, v) for u in range(graph.n_vertices)
for v in graph.adjacency_list[u]):
if subtrees[u] != subtrees[v]:
tree.append((u, v))
subtrees.union(u, v)
return tree
示例4: test_getitem_returns_proper_root
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def test_getitem_returns_proper_root(self):
union_find = UnionFind()
union_find.union('parent', 'first_child')
union_find.union('first_child', 'last_child')
self.assertEqual(union_find['parent'], 'parent')
self.assertEqual(union_find['first_child'], 'parent')
self.assertEqual(union_find['last_child'], 'parent')
示例5: MinimumSpanningTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def MinimumSpanningTree(V,E,W):
"""
Return the minimum spanning tree of an undirected graph G=(V,E) with total its cost.
W is a weights dictionary containing weight w of edge (u,v)
as the dict entry W[(u,v)] = W[(v,u)] = w (W should be symmetric).
The tree is returned as a list of edges.
Notes: Kruskal's algorithm for minimum spanning
Adpated from D. Eppstein' implementation (April 2006 version).
"""
from UnionFind import UnionFind # used for forests manipulation
# Kruskal's algorithm: sort edges by weight, and add them one at a time.
# We use Kruskal's algorithm, first because it is very simple to
# implement once UnionFind exists, and second, because the only slow
# part (the sort) is sped up by being built in to Python.
subtrees = UnionFind()
tree = []
#edges = [(G[u][v],u,v) for u in G for v in G[u]]
edges = [(W[(u,v)],u,v) for (u,v) in E]
edges.sort()
cost = 0.0
for w,u,v in edges:
if subtrees[u] != subtrees[v]:
tree.append((u,v))
subtrees.union(u,v)
cost+=w
return (tree,cost)
示例6: KruskalMST
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def KruskalMST(graph:EdgeWeightedGraph):
MST = []
EdgeSequence=[]
UF = UnionFind(graph.numVertices())
#Pre-processing the edges
PQ = []
for item in graph.adj:
PQ += graph.adj[item]
heapq.heapify(PQ)
while (len(PQ)>0) & (len(MST) < graph.numVertices()-1):
e = heapq.heappop(PQ)
v = e.either()
w = e.other(v)
if (UF.connected(v,w)):
continue
else:
UF.union(v,w)
heapq.heappush(MST, e)
EdgeSequence.append(e)
cluster = set()
for item in UF.id:
cluster.add(item)
print ("cluster:", cluster, len(cluster))
print (e.weight)
return MST
示例7: MinimumSpanningTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def MinimumSpanningTree(self):
"""
Return the minimum spanning tree of an undirected graph .
self.graph should be represented in such a way that self.graph[u][v] gives the
length of edge u,v, self.graph[u] should give the list of the neighbours,
and self.graph[u][v] should always equal self.graph[v][u].
self.graph should be a dictionary where each key is a vertex in the graph and
each value is a dictionary of destination:weight pairs
The tree is returned as a list of edge tuples.
Should adapt to use Numpy?
"""
# Kruskal's algorithm: sort edges by weight, and add them one at a time.
# We use Kruskal's algorithm, first because it is very simple to
# implement once UnionFind exists, and second, because the only slow
# part (the sort) is sped up by being built in to Python.
subtrees = UnionFind()
tree = []
# edges are found on initialization
self.edges.sort()
#print self.edges
for W,u,v in self.edges:
if self.verbose: print subtrees
if subtrees[u] != subtrees[v]:
tree.append((u,v))
subtrees.union(u,v)
self.m_s_tree = tree
示例8: foodHeuristic
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def foodHeuristic(state, problem):
position, foodGrid = state
"*** YOUR CODE HERE ***"
nodes = foodGrid.asList()
nodes.append(position)
G = {}
for p1 in nodes:
for p2 in nodes:
dist1 = p1,p2
dist2 = p2,p1
if p1<p2:
if dist1 in problem.heuristicInfo:
dist = problem.heuristicInfo[dist1]
elif dist2 in problem.heuristicInfo:
dist = problem.heuristicInfo[dist2]
else:
dist = mazeDistanceAStar(p1, p2, problem.getStartingGameState())
#dist = manDistance(p1, p2)
problem.heuristicInfo[p1,p2] = dist
G[p1,p2] = G[p2,p1] = dist
if p1 == p2:
G[p1,p2] = 0
subtrees = UnionFind()
edges = [(G[p1,p2],p1,p2) for p1 in nodes for p2 in nodes ]
edges.sort()
hDistance = 0
for W,u,v in edges:
if subtrees[u] != subtrees[v]:
hDistance += W
subtrees.union(u,v)
return hDistance
示例9: kcluster
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def kcluster(nodeset, edgeset, num_clusters, k):#WRONG
"""
Standard Algorithm
"""
#TODO: Validate Edgecase when k> len(nodeset) or len(edgeset)
# Sort edgeset by Cost
sorted_edges = sorted(edgeset, key=lambda x: x[2])
# Add each node to nodeset into UnionFind S
uf = UnionFind()
for node in nodeset:
uf[node]
# For each edge (u,v) in edgeset
for edge in sorted_edges:
#print 'Num Clusters {0}'.format(uf.size())
head, tail, wt = edge
if num_clusters == k:
print "STOP {0}".format(edge)
max_crossing = wt
return (uf , wt)
if uf[head] != uf[tail]:
uf.union(head, tail)
num_clusters -=1
return (uf , wt)
示例10: __getTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def __getTree(self):
# Sort edges by decreasing pheromone levels
self.edgeInfos.sort(key=geteiPheromoneLevel, reverse=True)
start = 0
# Current edges that will be inspected
C = []
# Data structure for Kruskal's algorithm
subtrees = UnionFind()
solution = []
degrees = defaultdict(int) # Map of degrees for each vertice
# While we don't have n-1 edges in our solution
while len(solution) != self.n - 1:
# Pick the the next nCanditates edges
C = self.edgeInfos[start : start + self.nCandiates]
# Sort the edge selection by increasing cost
C.sort(key=geteiCost)
start += self.nCandiates
for ei in C:
u, v = ei.u, ei.v
# Test if edge can be added to the current solution
if subtrees[u] != subtrees[v] and \
degrees[u] < self.d and degrees[v] < self.d: # Check constraint
solution.append(ei)
# Increment degrees of vertices of the added edge
degrees[u] += 1
degrees[v] += 1
# Update subtrees
subtrees.union(u, v)
return solution
示例11: minimumSpanningTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def minimumSpanningTree(edges):
subtrees = UnionFind()
tree = []
for e in edges:
if subtrees[e.v1] != subtrees[e.v2]:
tree.append(e)
subtrees.union(e.v1,e.v2)
e.v1.degree += 1
e.v2.degree += 1
return tree
示例12: GetMinimumSpanningTree
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def GetMinimumSpanningTree(graph):
subtrees = UnionFind()
spanningTree = WeightedGraph()
sorted_weighted_edges_list = sorted(
[(u, v, graph[u][v]) for u in graph for v in graph[u]],
key=lambda item: item[-1]
)
for u, v, w in sorted_weighted_edges_list:
if subtrees[u] != subtrees[v]:
spanningTree.AddEdge(u, v, w)
subtrees.union(u, v)
return spanningTree
示例13: kruskalsMST
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def kruskalsMST(self):
edges = self.sortedGraph
uf = UnionFind()
T = []
total_cost = 0
for cost,source,target in edges:
s1,s2 = uf[source],uf[target]
if s1 != s2 :
uf.union(s1,s2)
T.append((source,target))
total_cost += cost
return total_cost
示例14: segmentIsland
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def segmentIsland(flatFaces,island):
sets = UnionFind(True)
if len(island)==0:
island = range(len(flatFaces))
for face in island:
if face not in sets.leader.keys():
sets.makeSet([face])
neighbor = flatFaces[face].fromFace
if neighbor != None:
if neighbor not in sets.leader.keys():
sets.makeSet([neighbor])
sets.union(face,neighbor)
return sets.group, sets.leader
示例15: importGraph
# 需要导入模块: from UnionFind import UnionFind [as 别名]
# 或者: from UnionFind.UnionFind import union [as 别名]
def importGraph(filename = 'clustering2.txt'):
"""Imports pairs of endpoints into an adjancey list graph representation.
Keep track of both edges and vertices."""
f = open(filename)
(totalnodes, bits) = [int(x) for x in f.readline().split()]
nodecount = 0
nodes = {}
for line in f:
nodes[nodecount] = [int(x) for x in line.split()]
nodecount += 1
f.close()
count = 0
buckets = {}
# prep buckets
for i in range(0, bits - 1):
for j in range(i + 1, bits):
buckets[(i, j)] = {}
# print i, j
count += 1
print count
count = 0
for nkey, nval in nodes.items():
count += 1
if count % 1000 == 0:
print count
for i in range(0, bits - 1):
for j in range(i + 1, bits):
nvalminustwo = tuple(nval[0:i] + nval[i+ 1:j] + nval[j+1: bits])
if not buckets[(i, j)].has_key(nvalminustwo):
buckets[(i, j)][nvalminustwo] = [nkey]
else:
buckets[(i, j)][nvalminustwo].append(nkey)
uf = UnionFind()
for n in xrange(len(nodes)):
uf[n]
count = 0
for key in buckets.keys():
for valkey in buckets[key]:
count += 1
if count % 1000000 == 0:
print count
uf.union(*buckets[key][valkey])
return uf