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


Python priorityQueue.PriorityQueue类代码示例

本文整理汇总了Python中priorityQueue.PriorityQueue的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue类的具体用法?Python PriorityQueue怎么用?Python PriorityQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: singleSourceShortestPath

    def singleSourceShortestPath(self, srcID):
        assert (srcID >= 0 and srcID < self.n)
        # Implement Dijkstra's algorithm
        # Input:
        # self --> a reference to a MyGraph instance
        # srcID: the id of the source vertex.
        # Expected Output: (d,pi)
        #    d  --> Map each vertex id v to the distance from srcID
        #    pi --> Map each reachable vertex id v (except for srcID) to a parent.

        # Initialize the priority queue
        pq = PriorityQueue(self.n) #create the priority queue
        
        for i in range(0,self.n): # Iterate through all vertex ID
            if ( i == srcID):     # If ID is srcID
                pq.set(i,0.0)     # Distance of srcID should be zero
            else:                 # ID is not srcID
                pq.set(i, pq.Inf) # Distance should be infinity
        
        d = {}  # Initialize the map with distances to nodes
        pi = {} # Initialize the map with parents of vertices
        
        # COMPLETE the Dijkstra code here

            
        return (d,pi)
开发者ID:Bhawth,项目名称:csci3104_Assignment3,代码行数:26,代码来源:myGraph.py

示例2: color_most_constrained_first

def color_most_constrained_first(graphs, color):
    global spills, unspillable, num_unused, used_registers

    #print 'starting color_most_constrained_first'
    
    for v in graphs.vertices():
        used_registers[v] = set([])
        num_unused[v] = len(registers) - len(used_registers[v])

    left = set(graphs.vertices()) - set(reserved_registers) - set(registers)
    queue = PriorityQueue(left, avail_reg_then_unspill)

    while not queue.empty():
        v = queue.pop()
        if debug:
            print 'next to color is ' + v
        if v not in color.keys():
            c = choose_color(v, color, graphs,False)
            color[v] = c
            for u in graphs.interferes_with(v):
                #if u in graphs.vertices():
                queue.update(u)
                used_registers[u] |= set([c])
                num_unused[u] = len(registers) - len(used_registers[u])
                
            if not is_reg(c):
                spills += 1

    return color
开发者ID:parthmishra,项目名称:p0,代码行数:29,代码来源:registerAlloc1.py

示例3: solveUCS

 def solveUCS(self):
     #Initialize priority queue and fill it with the first connecting nodes
     pq = PriorityQueue()
     for edge in self.graph[self.start]:
         pq.push(edge,self.start,edge[1])
     #Recurse
     path = []
     self.rsolveUCS(pq,path)
     path.append(self.start)
     return path
开发者ID:bdubin1,项目名称:AIProject1,代码行数:10,代码来源:graph.py

示例4: dijkstra

def dijkstra(graphObj, startVertex):
    pq = PriorityQueue()

    for vertex in graphObj.getVertices():
        if vertex == startVertex:
            pq.insert([0, vertex])
            graphObj.verticesList[startVertex].distance = 0
        else:
            pq.insert([INFINITY, vertex])

    while(len(pq.pqueue)):
        currentVertex = pq.extractMin()

        if len(pq.pqueue) == 1:
            break

        # print(pq.pqueue, pq.lookup)
        for adjNode in graphObj.verticesList[currentVertex[1]].getConnections():
            newDistance = graphObj.verticesList[currentVertex[1]].distance + graphObj.verticesList[currentVertex[1]].adjList[adjNode]
            if newDistance < graphObj.verticesList[adjNode].distance:
                graphObj.verticesList[adjNode].distance = newDistance
                graphObj.verticesList[adjNode].predecessor = currentVertex[1]
                index = pq.lookup[adjNode]
                pq.decreaseKey(index, newDistance)

    return graphObj
开发者ID:AjithPanneerselvam,项目名称:Algorithm,代码行数:26,代码来源:dijkstra.py

示例5: __init__

 def __init__(self,newsSeedList,socialSeedList,govSeedList):        
     self.turn = 0
     '''
     if newsSeedList is not None:
         self.newsQueue = PriorityQueue(newsSeedList)
     if socialSeedList is not None:
         self.socialQueue = PriorityQueue(socialSeedList)
     if govSeedList is not None:
         self.govQueue = PriorityQueue(govSeedList)
     '''
     self.newsQueue = PriorityQueue(newsSeedList)
     self.socialQueue = PriorityQueue(socialSeedList)
     self.govQueue = PriorityQueue(govSeedList)
     
     heapq.heapify(self.newsQueue.queue)
     heapq.heapify(self.socialQueue.queue)
     heapq.heapify(self.govQueue.queue)
开发者ID:JoeAcanfora,项目名称:ProjFocusedCrawler,代码行数:17,代码来源:ExtendedPriorityQueue.py

示例6: __init__

	def __init__(self, app, length, fps, synchronous):
		self.__app = app
		self.__events = PriorityQueue()
		self.__spf = 1/fps # seconds per frame
		self.__frame = 0
		self.__frameTime = -self.__spf
		self.__length = length
		self.__synchronous = synchronous
开发者ID:redyeti,项目名称:camela-2.5D,代码行数:8,代码来源:animation.py

示例7: prims

def prims(graphObj, start):
    pq = PriorityQueue()

    for vertex in graphObj.verticesList:
        if vertex == start:
            g.verticesList[vertex].distance = 0
            pq.insert([0, vertex])
            continue
        g.verticesList[vertex].distance = INFINITY
        pq.insert([INFINITY, vertex])

    while(len(pq.pqueue)):
        currentVertex = pq.extractMin()

        if len(pq.pqueue) == 1:
            return

        for adjNode in graphObj.verticesList[currentVertex[1]].getConnections():
            if adjNode in pq.lookup(adjNode):
                newDistance = graphObj.verticesList[currentVertex[1]].getCost(adjNode)
                if newDistance < graphObj.verticesList[adjNode].distance:
                    graphObj.verticesList[adjNode].distance = newDistance
                    graphObj.verticesList[adjNode].predecessor = currentVertex[1]

        return graphObj
开发者ID:AjithPanneerselvam,项目名称:Algorithm,代码行数:25,代码来源:prims.py

示例8: prim

def prim(aGraph, startVertex):
    # create a priority queue that uses distance as the value to determine priority and thus its position
    # use the distance to the vertex as the priority because while exploring the next vertex, want to explore the vertex that has the smallest distance
    # decreaseKey method used when the distance to a vertex that is already in the queue is reduced, and thus moves that vertex toward the front of the queue.
    pQueue = PriorityQueue()
    # initialize the state of the graph 
    for vertex in aGraph:
        # initialally all vertices values are = infinity (sys.maxint) because we assume the greatest value and then update appropiately
        vertex.setDistance(sys.maxsize)
        vertex.setPred(None)
    
    # distance represents distance from the startVertex, trivially 0 for the startVertex
    startVertex.setDistance(0)
    # key value pair
    # key is distance and vertex is the value
    pQueue.buildHeap([ (vertex.getDistance(), vertex) for vertex in aGraph ])
    
    while not pQueue.isEmpty():
        currentVertex = pQueue.delMin()
        # iterate over the currentVertex's edges
        for nextVertex in currentVertex.getConnections():
            # calculate the weight from currentVertex to nextVertex
            newCost = currentVertex.getWeight(nextVertex)
            
            # found a shorter path
            # node is not considered to be part of the spanning tree until it is removed from the priority queue.
            # nextVertex in pQueue means that vertex is not yet in the spanning tree so it is safe to add (ensures an acyclic graph)
            if nextVertex in pQueue and newCost< nextVertex.getDistance():
                # assign the predecessor appropiately
                nextVertex.setPred(currentVertex)
                # set a new distance on the nextVertex
                nextVertex.setDistance(newCost)
                # update the priorityQueue with the correct values
                pQueue.decreaseKey(nextVertex, newCost)
开发者ID:AbhishekShah212,项目名称:Cuddling-with-a-Python-,代码行数:34,代码来源:minSpanTree.py

示例9: dijkstra

def dijkstra(aGraph, startVertex):
    # create a priority queue that uses distance as the value to determine priority and thus its position
    # use the distance to the vertex as the priority because while exploring the next vertex, want to explore the vertex that has the smallest distance
    # decreaseKey method used when the distance to a vertex that is already in the queue is reduced, and thus moves that vertex toward the front of the queue.
    pQueue = PriorityQueue()
    
    # distance represents distance from the startVertex, trivially 0 for the startVertex
    # initialally all vertices values are = infinity (sys.maxint) because we assume the greatest value and then update appropiately
    startVertex.setDistance(0)
    
    # key value pair
    # key is distance and vertex is the value
    pQueue.buildHeap([ (vertex.getDistance(), vertex) for vertex in aGraph ])
    
    while not pQueue.isEmpty():
        currentVertex = pQueue.delMin()
        # iterate over the currentVertex's edges
        for nextVertex in currentVertex.getConnections():
            # distance of current vertex and the weight of it's edges
            newDistance = currentVertex.getDistance() + currentVertex.getWeight(nextVertex)
            # found a shorter path
            if newDistance < nextVertex.getDistance():
                # set a new distance on the nextVertex
                nextVertex.setDistance(newDistance)
                # assign the predecessor appropiately
                nextVertex.setPred(currentVertex)
                # update the priorityQueue with the correct values
                pQueue.decreaseKey(nextVertex, newDistance)
开发者ID:AbhishekShah212,项目名称:Cuddling-with-a-Python-,代码行数:28,代码来源:dijkstraAlgorithm.py

示例10: solveUCS

    def solveUCS(self):
#        return ["A","B","C"]
        visited = [self.start]
        q = PriorityQueue()
        if self.start == self.end:
            print("Graph already solved! start and end nodes are the same!")
        else:
            #Build Queue
            startNode = self.findNode(self.start)
            for child in startNode.children:
                print("ADDING",child,"PARENT",startNode.name)
                q.put((child,startNode.name,startNode.children[child]))
                visited.append(child)

            #Recursively solve
            path = []
            self.rsolveUCS(q,path,visited)
            path.append(self.start)
            return path
开发者ID:UMBC-AI,项目名称:AIProject1,代码行数:19,代码来源:graph.py

示例11: Dijkstras

def Dijkstras(graph,start):   
	pq=PriorityQueue()
	start.setDistance(0)
	pq.buildHeap([(v.getDistance(),v) for v in graph])   # distance is the key in the priority queue
	while not pq.isEmpty():
		currentvertex=pq.delMin()
		for newvertex in currentvertex.getConnections():
			newDist=currentvertex.getDistance()+currentvertex.getWeight(newvertex)
			if newDist<newvertex.getDistance(): 
				# at the start the distance of all the vertices is set to maximum. That's why the if statement will be executed
				newvertex.setDistance(newDist)
				newvertex.setPredecessor(currentvertex)
				pq.decreaseKey(newvertex,newDist)
开发者ID:yashk2810,项目名称:Algorithms,代码行数:13,代码来源:dijkstras.py

示例12: __init__

class Sim:
    def __init__(self):
        self.q = PriorityQueue()
        self.time = 100
        self.nodes = {}
        self.actors = []
        self.done = False

    def add_actor(self, actor):
        actor.sim = self
        self.actors.append(actor)

    def at(self, event):
        if event.time < self.time:
            print "ERROR, time warp"
        else:
            self.q.put(event, event.time)

    def process(self):
        while not self.q.empty():
            event = self.q.get()
            self.time = event.time
            try:
                (result, actor) = event.process(self)
                actor.send(result)
            except StopIteration:
                pass
        print "Sim done"

    def prime(self):
        for a in self.actors:
            a.prime()

    def go(self):
        self.prime()
        self.process()
开发者ID:krohan100,项目名称:pydssim,代码行数:36,代码来源:simdd.py

示例13: prim

def prim(graph,start):     # it belongs to the family of greedy algorithms
	pq=PriorityQueue()
	for v in graph:
		v.setDistance(sys.maxsize)
		v.setPredecessor(None)
	start.setDistance(0)
	pq.buildHeap([(v.getDistance(),v) for v in graph])
	while not pq.isEmpty()
		currentvertex=pq.delMin()
		for newvertex in currentvertex.getConnections():
			newDist=currentvertex.getWeight(newvertex)
			if newDist<newvertex.getDistance() and newvertex in pq:
				newvertex.setDistance(newDist)
				newvertex.setPredecessor(currentvertex)
				pq.decreaseKey(newvertex,newDist)
开发者ID:yashk2810,项目名称:Algorithms,代码行数:15,代码来源:prims.py

示例14: representativeNodes

def representativeNodes(G, k, metric=1):
    ''' Finds the most distinguishable (representative) nodes in graph G greedily.
    Takes the most furthest node to the already chosen nodes at each step.

    Input: G -- networkx object graph with weighted edges
    k -- number of nodes needed
    metric -- parameter for differentiating representative qualities
    metric == 1 trying to maximize total distance in the chosen set of k nodes
    metric == 2 trying to maximize minimal distance between a pair of k nodes
    Output:
    S -- chosen k nodes
    objv -- objective value according to the chosen metric and set of nodes
    '''

    S = [] # set of chosen nodes
    S_dist = PQ() # distances from each node in G to set S according to metric

    # initialize S with furthest vertices
    try:
        u,v,d = max(G.edges(data=True), key=lambda (u, v, d): d['weight'])
    except KeyError:
        raise KeyError, 'Most likely you have no weight attribute'
    S.extend([u,v])

    # compute distances from each node in G to S
    for v in G.nodes():
        if v not in S: # calculate only for nodes in G
            if metric == 1:
                S_dist.add_task(v, - _sumDist(G, S, v)) # take minus to pop the maximum value from priority queue
            elif metric == 2:
                S_dist.add_task(v, - _minDist(G, S, v)) # take minus to pop the maximum value from priority queue

    # add new nodes to the set greedily
    while len(S) < k:
        u, priority = S_dist.pop_item() # find maximum value of distance to set S
        S.append(u) # append that node to S

        # only increase distance for nodes that are connected to u
        for v in G[u].keys():
            if v not in S: # add only remained nodes
                [priority, count, task] = S_dist.entry_finder[v] # finds distance for the previous step
                try:
                    if metric == 1:
                        S_dist.add_task(v, priority-G[u][v]['weight']) # adds distance to the new member of S
                    elif metric == 2:
                        S_dist.add_task(v, max(priority, -G[u][v]['weight'])) # update min distance to the set S
                except:
                    raise u,v, "These are vertices that caused the problem"

    # extract objective value of the chosen set
    if metric == 1:
        objv = 0
        for u in S:
            objv += _sumDist(G, S, u)
    elif metric == 2:
        objv = float('Inf')
        for u in S:
            objv = min(objv, _minDist(G, S, u))

    return S, objv
开发者ID:tempcyc,项目名称:influence-maximization,代码行数:60,代码来源:representativeNodes.py

示例15: degreeHeuristic

def degreeHeuristic(G, k, p=.01):
    ''' Finds initial set of nodes to propagate in Independent Cascade model (with priority queue)
    Input: G -- networkx graph object
    k -- number of nodes needed
    p -- propagation probability
    Output:
    S -- chosen k nodes
    '''
    S = []
    d = PQ()
    for u in G:
        degree = sum([G[u][v]['weight'] for v in G[u]])
        # degree = len(G[u])
        d.add_task(u, -degree)
    for i in range(k):
        u, priority = d.pop_item()
        S.append(u)
    return S
开发者ID:tempcyc,项目名称:influence-maximization,代码行数:18,代码来源:degreeHeuristic.py


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