当前位置: 首页>>代码示例>>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;未经允许,请勿转载。