本文整理汇总了Python中PriorityQueue.PriorityQueue.pop方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.pop方法的具体用法?Python PriorityQueue.pop怎么用?Python PriorityQueue.pop使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PriorityQueue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.pop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: astar
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def astar(start, successors, goal, g, h):
path = []
states = PriorityQueue()
firststate = start
states.put((-g(firststate) - h(firststate), firststate))
i = 0
nexti = 1
while True:
i += 1
# if i == 40000:
# return (0, None)
if i == nexti:
nexti += 1 # 3*len(states)
curbest = states.top()[1]
print "%8d: # states: %5d, h of best state: %5d" % (i, len(states), h(curbest))
print "\tcurrent top: score = %6d; %r" % (g(curbest) + h(curbest), curbest)
try:
if goal(states.top()[1]):
print i
return (states.top()[1], g(states.top()[1]))
except IndexError:
return (0, None)
best = states.top()[1]
states.pop()
for s in successors(best):
prev = [x for x in states if x[1] == s]
# if len(prev)>0:print prev[0][1]
# print s
if len(prev) > 0 and g(s) < g(prev[0][1]):
states.remove(prev[0])
if len(prev) > 0:
continue
states.put((-g(s) - h(s), s))
示例2: FindDirections
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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)
示例3: astar
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def astar(start, successors, goal, g, h):
path = []
states = PriorityQueue()
firststate = (start,None)
states.put((-g(firststate) - h(firststate), firststate))
i = 0
while True:
i += 1
if i % 2500 == 0:
print '%8d: # states: %5d, h of best state: %5d' % \
(i, len(states), min(h(state[1]) for state in states))
try:
if goal(states.top()[1]):
return g(states.top()[1]), getpath(states.top()[1])
except IndexError:
return None
best = states.top()[1]
states.pop()
for s in successors(best):
prev = [x for x in states if x[1][0] == s]
s = (s, best)
#if len(prev)>0:print prev[0][1]
#print s
if len(prev) > 0 and g(s) < g(prev[0][1]):
states.remove(prev[0])
if len(prev) > 0:
continue
states.put((-g(s) - h(s), s))
示例4: test_multiple
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def test_multiple(self):
'''Test that two different priority queues do not interfere with
each other'''
pq = PriorityQueue()
pq.push(0, 'A')
pq = PriorityQueue()
self.assertEqual(len(pq), 0)
with self.assertRaises(IndexError):
pq.pop()
示例5: test_dict
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def test_dict(self):
'''Push a dictionary'''
pq = PriorityQueue()
d = {'a':10, 'b':4}
pq.push(0, d)
self.assertEqual(pq.pop()[1], d)
示例6: test_uselist
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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))
示例7: test_pushpop
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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)
示例8: run
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def run(self, gridMap, defStartNode=None, defEndNode=None, distanceType=PFA.DIS_TYPE_MANHATTAN):
if not gridMap:
return (PFA.RSLT_GRIDMAP_ERR,)
startNode = defStartNode
if not startNode:
startNode = gridMap.getStartGridNode()
if not startNode:
return (PFA.RSLT_NO_START_NODE,)
endNode = defEndNode
if not endNode:
endNode = gridMap.getEndGridNode()
if not endNode:
return (PFA.RSLT_NO_END_NODE,)
hdis = self.getDistance(startNode, endNode, distanceType)
if hdis < 0:
return (PFA.RSLT_DIS_INVALID,)
self.gridMap = gridMap
self.initPathMap(gridMap, distanceType)
openSet = PQ()
startPathNode = self.pMap[startNode.x][startNode.y]
openSet.push(startPathNode)
endPathNode = self.pMap[endNode.x][endNode.y]
ret = (PFA.RSLT_NONE,)
jumpPoint = []
while not openSet.isEmpty() and ret[0] == PFA.RSLT_NONE:
currNode = openSet.pop()
jumpPoint.append(currNode)
currNode.isInClose = True
currGridNode = currNode.gridNode
if gridMap.isEndGridNode(currGridNode.x, currGridNode.y):
ret = (PFA.RSLT_OK, self.genValidPath(gridMap), self.genAllVisNodeSet(gridMap), jumpPoint)
break
for i in range(len(self.visMap)):
for j in range(len(self.visMap[i])):
self.visMap[i][j] = False
for dv in PFA.DIR_VECTOR:
if not self.isOkPos(currGridNode, dv):
continue
jumpNode = self.findJumpNode(currNode, currNode, self.getPathNode(currGridNode, dv), openSet)
if jumpNode:
self.updateJumpNode(currNode, jumpNode, openSet)
return ret
示例9: fast_marching_method
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def fast_marching_method(graph,start):
h = 1
def calculus_distance(node,graph,weights):
neighbours = graph.get_neighbours(node);
if 'y-1' in neighbours :
if 'y+1' in neighbours:
x1 = min(weights[neighbours['y-1']],weights[neighbours['y+1']]);
else :
x1 = weights[neighbours['y-1']];
else :
if 'y+1' in neighbours:
x1 = weights[neighbours['y+1']];
if 'x-1' in neighbours:
if 'x+1' in neighbours:
x2 = min(weights[neighbours['x-1']],weights[neighbours['x+1']]);
else :
x2 = weights[neighbours['x-1']];
else :
if 'x+1' in neighbours:
x2 = weights[neighbours['x+1']];
if 2*h**2-(x1-x2)**2>=0:
return (x1+x2+(2*h**2-(x1-x2)**2)**0.5)/2
else:
return min(x1,x2)+h
frontier = PriorityQueue();
weights = graph.distances;
explored = []
goals = numpy.where(graph.indicator_map==2)
goals_x = goals[0]
goals_y = goals[1]
for i in range(goals_x.size):
frontier.append([0,(goals_x[i],goals_y[i])])
weights[(goals_x[i],goals_y[i])] = 0
while frontier:
node = frontier.pop();
explored.append(node[1])
#if node[1]==start:
# return weights
neighbours = graph.get_neighbours(node[1]);
for neighbour in neighbours.itervalues():
if neighbour not in explored and graph.indicator_map[neighbour]:
if not neighbour in frontier:
frontier.append([calculus_distance(neighbour,graph,weights),neighbour])
weights[neighbour]=calculus_distance(neighbour,graph,weights)
elif weights[neighbour] > calculus_distance(neighbour,graph,weights):
frontier[neighbour][0]=calculus_distance(neighbour,graph,weights)
weights[neighbour]=calculus_distance(neighbour,graph,weights)
graph.distances = weights
示例10: dijkstra
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
def dijkstra(self, start, goal, exceptions=None):
'''Dijkstra's algorithm, conceived by Dutch computer scientist Edsger
Dijkstra in 1956 and published in 1959, is a graph search algorithm
that solves the single-source shortest path problem for a graph with
nonnegative edge path costs, producing a shortest path tree.
.. note::
Unmodified, Dijkstra's algorithm searches outward in a circle from
the start node until it reaches the goal. It is therefore slower
than other methods like A* or Bi-directional Dijkstra's. The
algorithm is included here for performance comparision against
other algorithms only.
.. seealso::
:func:`aStarPath`, :func:`dijkstraBi`
'''
dist = {} # dictionary of final distances
came_from = {} # dictionary of predecessors
# nodes not yet found
queue = PriorityQueue()
# The set of nodes already evaluated
closedset = []
queue.push(0, start)
while len(queue) > 0:
#log.debug("queue: " + str(queue))
weight, x = queue.pop()
dist[x] = weight
if x == goal:
#log.debug("came_from: " + str(came_from))
path = self.reconstructPath(came_from, goal)
#log.info("Path: %s" % path)
return path
closedset.append(x)
for y in self.neighborNodes(x):
if y in closedset:
continue
if(exceptions is not None and y in exceptions):
continue
costxy = self.timeBetween(x,y)
if not dist.has_key(y) or dist[x] + costxy < dist[y]:
dist[y] = dist[x] + costxy
queue.reprioritize(dist[y], y)
came_from[y] = x
#log.debug("Update node %s's weight to %g" % (y, dist[y]))
return None
示例11: test_neg_priority
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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)
示例12: alternateRoute
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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
示例13: test_priority
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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)
示例14: PriorityQueueTest
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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())
示例15: FindDirections
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import pop [as 别名]
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