當前位置: 首頁>>代碼示例>>Python>>正文


Python PriorityQueue.PriorityQueue類代碼示例

本文整理匯總了Python中PriorityQueue.PriorityQueue的典型用法代碼示例。如果您正苦於以下問題:Python PriorityQueue類的具體用法?Python PriorityQueue怎麽用?Python PriorityQueue使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了PriorityQueue類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_uselist

    def test_uselist(self):
        '''Push a list onto queue and them remove it'''
        pq = PriorityQueue()
        l = []

        pq.push(0,range(0, 10))
        self.assertEqual(pq.pop()[1], range(0, 10))
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:7,代碼來源:UnitTestPriorityQueue.py

示例2: test_dict

 def test_dict(self):
     '''Push a dictionary'''
     pq = PriorityQueue()
     d = {'a':10, 'b':4}
     
     pq.push(0, d)
     self.assertEqual(pq.pop()[1], d)
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:7,代碼來源:UnitTestPriorityQueue.py

示例3: test_pushpop

 def test_pushpop(self):
     '''Push items onto queue and then remove them'''
     pq = PriorityQueue()
     for i in range(0, 10):
         pq.push(0,i)
         
     for i in range(0, 10):
         self.assertEqual(pq.pop()[1], i)
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:8,代碼來源:UnitTestPriorityQueue.py

示例4: __init__

class PriorityEdgeList:
    def __init__(self):
        self.edges = []
        self.priorityEdges = PriorityQueue()
        self.empty = True

    def InsertEdge(self, y, w):
        self.priorityEdges.add_task(y, w)
        self.edges.append( Graphs.Edge(y,w))
        self.empty = False
開發者ID:QualityCodePassion,項目名稱:Uni-Alg,代碼行數:10,代碼來源:Prims.py

示例5: primsAlgorithm

def primsAlgorithm(graph, start, surface):
    
    for v in graph:
        v.setStatus(0)
        v.setParent(None)
        
    pq = PriorityQueue()
    #heapq.heappush(pq, (0, start))
    pq.enQueue((0, start))
    while (not pq.isEmpty()):
        current = pq.deQueue()[1]
        current.setStatus(2)
        if(current.getParent() != None):
            graph.drawEdge(current.getParent(), current, surface, "yellow")
            time.sleep(0.5)
            #print(str(current.getParent().getId()) + "->" + str(current.getId()))
        for neighbour in current.getNeighbours():
                    if (neighbour.getStatus() == 0):        
                        neighbour.setStatus(1)
                        neighbour.setParent(current)
                        neighbour.setpqWeight(current.neighbours[neighbour])
                        #print(str(neighbour.getpqWeight()))
                        pq.enQueue((neighbour.getpqWeight(), neighbour))
                    elif (neighbour.getStatus() == 1):
                        if (neighbour.getpqWeight() > current.neighbours[neighbour]):
                            old = (neighbour.getpqWeight(), neighbour)
                            neighbour.setpqWeight(current.neighbours[neighbour])
                            pq.updatePriority(old, (neighbour.getpqWeight(), neighbour))
                            neighbour.setParent(current)    
    """
開發者ID:KarlParkinson,項目名稱:Graphs,代碼行數:30,代碼來源:Graphing.py

示例6: prims

 def prims(self, graph, start, canvas):
     for v in graph:
         v.setStatus(0)
         v.setParent(None)
             
     pq = PriorityQueue()
     pq.enQueue((0, start))
     while (not pq.isEmpty()):
         current = pq.deQueue()[1]
         current.setStatus(2)
         if(current.getParent() != None):
             graph.drawEdge(current.getParent(), current, canvas, "yellow")
             canvas.update()
             time.sleep(0.5)
         for neighbour in current.getNeighbours():
             if (neighbour.getStatus() == 0):  
                 # Encountered a new vertex
                 neighbour.setStatus(1)
                 neighbour.setParent(current)
                 neighbour.setpqWeight(current.neighbours[neighbour])
                 pq.enQueue((neighbour.getpqWeight(), neighbour))
             elif (neighbour.getStatus() == 1):
                 if (neighbour.getpqWeight() > current.neighbours[neighbour]):
                     # Found smaller weight, update accordingly
                     old = (neighbour.getpqWeight(), neighbour)
                     neighbour.setpqWeight(current.neighbours[neighbour])
                     pq.updatePriority(old, (neighbour.getpqWeight(), neighbour))
                     neighbour.setParent(current)
開發者ID:KarlParkinson,項目名稱:Graphs,代碼行數:28,代碼來源:AlgorithmHandler.py

示例7: test_priority

 def test_priority(self):
     '''Test the priority portion of the priority queue'''
     pq = PriorityQueue()
     for i in range(0, 10):
         pq.push(i,i)
         
     for i in range(0, 10):
         pri, item = pq.pop()
         # Priorities match
         self.assertEqual(pri, i)
         # Values match
         self.assertEqual(item, i)
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:12,代碼來源:UnitTestPriorityQueue.py

示例8: alternateRoute

    def alternateRoute(self, num, optimal_path):
        '''To obtain a ranked list of less-than-optimal solutions, the optimal 
        solution must first calculated. This optimal solution is passed in as
        ``optimal_path``. A single edge appearing in the optimal solution is 
        removed from the graph, and the optimum solution to this new graph is 
        calculated. Each edge of the original solution is suppressed in turn
        and a new shortest-path calculated. The secondary solutions are then
        ranked and the ``num`` best sub-optimal solutions are returned. If 
        less than ``num`` solutions exist for the given graph, less than
        ``num`` solutions will be returned. The results are a list of tuples
        of form: 
        ``((cost, path), (cost2, path2), ...)``
        
        An example of finding alternate routes::
        
            search = Pathfinding()
            # find optimal route
            optimal_path = search.shortestPath("A", "E")
            # returns ["A", "C", "E"]
            cost = search.pathCost(optimal_path)
            # returns 3
            alt_paths = search.alternateRoute(2, optimal_path)
            # returns ((4, ["A", "B", "D", "E"]), (4, ["A", "B", "F", "E"]))
        '''
        
        # Store the paths by their weights in a priority queue. The paths with
        # the lowest cost will move to the top. At the end, pop() the queue
        # once for each desired alternative.
        minheap = PriorityQueue()
        
        start, goal = optimal_path[0], optimal_path[-1]
        
        # Don't remove the start or goal nodes
        for i in range(1, len(optimal_path) - 1):
            y = optimal_path[i]
            
            log.info("Look for sub-optimal solution with vertex {} removed".\
                    format(y))
            path = self.shortestPath(start, goal, [y])
            #path = self.shortestPath(start, goal)
            cost = self.pathCost(path)
            
            log.debug("Cost of path with vertex %s removed is %g" \
                                    % (y, cost))
            minheap.push(cost, path)

        alternatives = []
        for i in range(0, min(num, len(minheap))):
            cost, path = minheap.pop()
            alternatives.append((cost,path))
            log.debug("Cost of #%d sub-optimal path is %g" % (i+1, cost))
            
        return alternatives
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:53,代碼來源:Pathfinding.py

示例9: test_neg_priority

 def test_neg_priority(self):
     '''Negative priorities'''
     pq = PriorityQueue()
     for i in range(-5, 5):
         pq.push(i,i)
         
     for i in range(-5, 5):
         pri, item = pq.pop()
         # Priorities match
         self.assertEqual(pri, i)
         # Values match
         self.assertEqual(item, i)
開發者ID:steven-nichols,項目名稱:ShortQut,代碼行數:12,代碼來源:UnitTestPriorityQueue.py

示例10: PriorityQueueTest

class PriorityQueueTest(unittest.TestCase):
    def setUp(self):
        self.p_queue = PriorityQueue()

    def test(self):
        elements = []
        for i in range(1000):
            x = random()
            elements.append(x)
            self.p_queue.insert(x)
        elements.sort(reverse=True)
        for elem in elements:
            self.assertEqual(elem, self.p_queue.pop())
開發者ID:KorobovMS,項目名稱:Algorithms,代碼行數:13,代碼來源:test.py

示例11: FindDirections

    def FindDirections(self, curState):
        pq = PriorityQueue(["dist", "changeDir"])
        pq.add({"state": curState, "prev": None, "dist": 0 + self.heuristics(curState), "changeDir": 0, "step": 0})
        cnt = 0
        while True:
            elem = pq.pop()
            #print("Dir:", elem["state"].snake.curDir, "step:", elem["step"], "cnt: ", cnt)

            ok_dirs = self._get_ok_dirs_(elem["state"])
            #print ok_dirs
            for d in ok_dirs:
                nextState = elem["state"].GetNextState(d)

                step = elem["step"] + 1
                changeDir = 0
                if d != elem["state"].snake.curDir:
                    changeDir = 1
                dist = step + self.heuristics(nextState)

                pq.add({"state": nextState, "prev": elem, "dist": dist, "changeDir":changeDir, "step": step} )

            #if elem["step"] % 10 == 0:
            #    print elem["step"]
            if pq.IsEmpty():
                print "EMPTY!!!!", elem["step"]
                if len(pq.storage) > 0:
                    elem = pq.storage.pop(0)
                    pq.add(elem)
                """
                while len(pq.storage) > 0:
                    other = pq.storage.pop()
                    print other["step"], elem["step"]
                    if abs(other["step"] - elem["step"]) < elem["step"] * 0.1:
                        break
                        """
                print elem["state"].IsAppleEaten(), elem["state"].apple.GetApplePos()
                #pq.add(other)

            cnt += 1
            if cnt >= 2000 or self._is_goal(elem["state"]) and elem["step"] > 0:
                #print("step:", elem["step"], "cnt:", cnt, "empty:", pq.IsEmpty())
                pq.clean()
                while True:
                    self.directions.append(elem["state"].snake.curDir)
                    elem = elem["prev"]
                    if elem is None:
                        break
                self.directions.pop() # remove the first direction (the state that already take a step)

                return self.directions
開發者ID:cyj907,項目名稱:snake,代碼行數:50,代碼來源:Astar.py

示例12: Prim

def Prim(G, w, s):
	inf = float("inf")
	H = PriorityQueue()
	T = []
	s.priorite = 0
	H.add_task(s, 0)
	i = 1
	for u in G.sommets:
		u.pred = None
		if u != s :
			H.add_task(u, inf)
			u.priorite = inf
	try:
		while True:
			u = H.pop_task()
			u.couleur = "noir"
			if u.priorite != inf:
				if u.pred is not None: T.append((u.pred, u))
				for v in u.voisins:
					if v.couleur == "blanc": #v n'est pas sorti du tas
						if w[(u, v)] < v.priorite:
							v.priorite = w[(u, v)]
							H.add_task(v, v.priorite)
							v.pred = u
	except:
		pass
	return T
開發者ID:XAMEUS,項目名稱:AL5,代碼行數:27,代碼來源:Prim.py

示例13: shortest_path

 def shortest_path(self, target):
     """
     Uses Dijkstra's algorithm to return the shortest paths between the 
     target and all other nodes in the graph.
     """
     if not self.weighted:
         print "Graph is not weighted; redirecting to BFS"
         return self.bfs(target, min_distance=True)
     distances_pq = PriorityQueue("min")
     distances_dict = {} 
     unvisited = []
     for node in self.adj_matrix[0]:
         if node == target:
             distances_pq.enqueue(0, node)
             distances_dict[node] = 0
         elif node != False:
             distances_pq.enqueue(float('inf'), node)
             distances_dict[node] = float('inf')
         else:
             continue
         unvisited.append(node)
     while unvisited:
         min_distance, min_node = distances_pq.dequeue()
         if min_node not in unvisited:
             continue
         neighbors = self.linked(min_node)
         for neighbor in neighbors:
             neighbor_distance = min(distances_dict[neighbor], 
                                     min_distance + self.link_weight(min_node, neighbor))
             if neighbor_distance != distances_dict[neighbor]:
                distances_dict[neighbor] = neighbor_distance
                distances_pq.enqueue(neighbor_distance, neighbor)
         unvisited.remove(min_node)
     return distances_dict
開發者ID:nikrdc,項目名稱:Python-Data-Structures-and-Algorithms,代碼行數:34,代碼來源:Graph.py

示例14: FindDirections

    def FindDirections(self, curState):
        self.directions = []
        pq = PriorityQueue(["dist"])
        maxDepth = 5
        pq.add({"state": curState, "dist": self.heuristics(curState), "step": 0, "prev": None})
        cnt = 0
        while not pq.IsEmpty():
            elem = pq.pop()
            state = elem["state"]
            stack = []
            stack.append({"state": state, "step": 0, "prev": elem["prev"]})

            """
            if cnt >= SCREEN_WITH + SCREEN_HEIGHT - 4 * SNAKE_WITH_HALH - 2:
                print "size of queue: ", len(pq.queue)
                cnt = 0
            """
            """
            maxSize = max(len(pq.queue) / 2, len(pq.queue) - randint(10, 20))
            reduceSize = min(maxSize, len(pq.queue) - 5)
            for i in range(reduceSize):
                pq.pop()

            """
            if len(pq.queue) > 700:
                # TODO: if we cannnot find solution for so long a time, the size of queue should
                # be reduced to a pretty small number
                for i in range(randint(0,len(pq.queue)-1)):
                    pq.pop()
                #print "size of queue: ", len(pq.queue)
                #print curState.snake.body
                #print curState.snake.GetBodyRects()
                continue

            while len(stack) > 0:
                el = stack.pop()
                stat = el["state"]

                if el["step"] >= maxDepth:
                    pq.add({"state": stat, "dist": self.heuristics(stat), "step": el["step"], "prev": el["prev"]})
                    continue

                if stat.IsAppleEaten():
                    # guess if the snake can be dead by instinct
                    stat.AddSnakeLen()
                    if self._is_possible_dead_(stat):
                        continue
                    while el is not None:
                        self.directions.append(el["state"].snake.curDir)
                        el = el["prev"]
                    self.directions.pop()
                    return

                ok_dirs = self._arange_dirs_(stat, self._get_ok_dirs_(stat))
                for d in ok_dirs:
                    nextStat = stat.GetNextState(d)
                    nextEl = {"state": nextStat, "step": el["step"]+1, "prev": el}
                    stack.append(nextEl)

        self.directions.append(Direction.Stop)
開發者ID:cyj907,項目名稱:snake,代碼行數:60,代碼來源:AIBDFS.py

示例15: dijkstrasAlgorithm

def dijkstrasAlgorithm(graph, start):
    for v in graph:
        v.setStatus(0)
        
    #start.setStatus(2)
    start.setDistance(0)
    pq = PriorityQueue()
    #heapq.heappush(pq, (0, start))
    pq.enQueue((0, start))
    while (not pq.isEmpty()):
        current = pq.deQueue()[1]
        current.setStatus(2)
        #if(current.getParent() != None):
            #  print(str(current.getParent().getId()) + "->" + str(current.getId()))
        for neighbour in current.getNeighbours():
            if (neighbour.getStatus() == 0):        
                neighbour.setStatus(1)
                neighbour.setParent(current)
                neighbour.setpqWeight(current.neighbours[neighbour])
                neighbour.setDistance(current.getDistance() + current.neighbours[neighbour])
                pq.enQueue((neighbour.getpqWeight(), neighbour))
            elif (neighbour.getStatus() == 1):
                if (neighbour.getDistance()) > (current.getDistance() + current.neighbours[neighbour]):
                    #old = (neighbour.getpqWeight(), neighbour)
                    #neighbour.setpqWeight(current.neighbours[neighbour])
                    #pq.updatePriority(old, (neighbour.getpqWeight(), neighbour))
                    neighbour.setParent(current)
                    neighbour.setDistance(current.getDistance() + current.neighbours[neighbour])
開發者ID:KarlParkinson,項目名稱:Graphs,代碼行數:28,代碼來源:Pathfinding.py


注:本文中的PriorityQueue.PriorityQueue類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。