本文整理汇总了Python中PriorityQueue.PriorityQueue.push方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.push方法的具体用法?Python PriorityQueue.push怎么用?Python PriorityQueue.push使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PriorityQueue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.push方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_dict
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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)
示例2: test_uselist
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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))
示例3: test_pushpop
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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)
示例4: run
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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
示例5: dijkstraBi
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [as 别名]
def dijkstraBi(self, start, goal, exceptions=None):
'''Bi-Directional Dijkstra's algorithm. The search begins at the
``start`` node and at the ``goal`` node simultaneously. The search area
expands radially outward from both ends until the two meet in the
middle. In most cases this reduces the number of vertices which must
be checked by half.
.. image:: dijkstra.png
.. image:: dijkstra-bidirectional.png
Search area of Dijkstra's algorithm (left) vs search area of
bi-directional Dijkstra's algorithm (right).
.. seealso::
:func:`aStarPath`, :func:`dijkstra`
'''
dist_f = {} # dictionary of final distances
dist_b = {} # dictionary of final distances
came_from_f = {} # dictionary of predecessors
came_from_b = {} # dictionary of predecessors
# nodes not yet found
forward = PriorityQueue()
backward = PriorityQueue()
# The set of nodes already evaluated
closedset_forward = []
closedset_backward = []
forward.push(0, start)
backward.push(0, goal)
while len(forward) + len(backward) > 0:
if len(forward) > 0:
done, stop = self.__dijkstraBiIter(start, goal, exceptions,
dist_f, came_from_f, forward,
closedset_forward, closedset_backward)
if not done and len(backward) > 0:
done, stop = self.__dijkstraBiIter(goal, start, exceptions,
dist_b, came_from_b, backward,
closedset_backward, closedset_forward)
if done:
#log.debug("came_from_f: " + str(came_from_f))
#log.debug("came_from_b: " + str(came_from_b))
pathf = self.reconstructPath(came_from_f, stop)
#log.info("PathF: %s" % pathf)
pathb = self.reconstructPath(came_from_b, stop)
pathb.reverse()
#log.info("PathB: %s" % pathb)
return pathf + pathb[1:]
return None
示例6: test_multiple
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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()
示例7: dijkstra
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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
示例8: test_neg_priority
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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)
示例9: test_priority
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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)
示例10: alternateRoute
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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
示例11: test_reprioritize
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [as 别名]
def test_reprioritize(self):
pq = PriorityQueue()
for letter in range(ord('A'), ord('Z')+1):
letter = chr(letter)
pq.push(0, letter)
pq.reprioritize(1, letter)
self.assertEqual(len(pq), 26, "Incorrect length")
for letter in range(ord('A'), ord('Z')+1):
letter = chr(letter)
pri, val = pq.pop()
self.assertEqual(letter, val)
self.assertEqual(pri, 1)
self.assertEqual(len(pq), 0, "Incorrect length")
示例12: getdist
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [as 别名]
def getdist(start, goal, m):
num_rows = len(m)
num_cols = len(m[0])
def h(n):
row1, col1 = n
row2, col2 = goal
d_col = min(abs(col1 - col2), num_cols - abs(col1 - col2))
d_row = min(abs(row1 - row2), num_rows - abs(row1 - row2))
return d_row + d_col
fringe = PriorityQueue()
closed = set()
fringe.push((start, 0), h(start))
while len(fringe) > 0:
f, (node, g) = fringe.pop()
if node in closed: continue
closed.add(node)
if node == goal: return g
y, x = node
suc = (y, (x+1)%num_cols)
if m[suc[1]][suc[0]] != WATER:
fringe.push((suc, g+1), g+1+h(suc))
suc = (y, (x-1)%num_cols)
if m[suc[1]][suc[0]] != WATER:
fringe.push((suc, g+1), g+1+h(suc))
suc = ((y+1)%num_rows, x)
if m[suc[1]][suc[0]] != WATER:
fringe.push((suc, g+1), g+1+h(suc))
suc = ((y-1)%num_rows, x)
if m[suc[1]][suc[0]] != WATER:
fringe.push((suc, g+1), g+1+h(suc))
return inf
示例13: run
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [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,)
self.initPathMap(gridMap, distanceType)
closeSet = PQ()
startPathNode = self.pMap[startNode.x][startNode.y]
closeSet.push(startPathNode)
endPathNode = self.pMap[endNode.x][endNode.y]
endPathNode.isInClose = True
ret = (PFA.RSLT_NONE,)
while not closeSet.isEmpty() and ret[0] == PFA.RSLT_NONE:
currNode = closeSet.pop()
currNode.isInClose = True
# print("%d,%d,%d" % (currNode.gridNode.x, currNode.gridNode.y,currNode.fv))
currGridNode = currNode.gridNode
for dv in PFA.DIR_VECTOR:
nx = currGridNode.x + dv[0]
ny = currGridNode.y + dv[1]
if not gridMap.isValidPos(nx, ny):
continue
if gridMap.isThroughTheWall(currGridNode.x, currGridNode.y, dv):
continue
gCost = self.getGCost(dv)
if gridMap.isEndGridNode(nx, ny):
endPathNode.updatePrev(currNode, gCost)
ret = (PFA.RSLT_OK, self.genValidPath(gridMap), self.genAllVisNodeSet(gridMap), None)
break
newNode = self.pMap[nx][ny]
if newNode:
if not newNode.isInClose:
newNode.isInClose = True
closeSet.push(newNode)
if currNode.gv + gCost < newNode.gv:
newNode.updatePrev(currNode, gCost)
closeSet.update(newNode)
# if newNode.isInClose:
# if currNode.gv + gCost < newNode.gv:
# newNode.isInClose = False
# newNode.updatePrev(currNode, gCost)
# openSet.push(newNode)
# newNode.isInOpen = True
# else:
# if currNode.gv + gCost < newNode.gv:
# newNode.updatePrev(currNode, gCost)
# if not newNode.isInOpen:
# openSet.push(newNode)
# newNode.isInOpen = True
# else:
# openSet.update(newNode)
return ret
示例14: PriorityQueue
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [as 别名]
from PriorityQueue import PriorityQueue
from Item import Item
q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),5)
q.push(Item('spam'),4)
q.push(Item('grok'),2)
print q.pop()
print q.pop()
print q.pop()
print q.pop()
a = (Item('foo'),1)
b = (Item('bar'),2)
print a>b
示例15: aStarPath
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import push [as 别名]
def aStarPath(self, start, goal, exceptions=None):
'''A* is an algorithm that is used in pathfinding and graph traversal.
Noted for its performance and accuracy, it enjoys widespread use. It
is an extension of Edger Dijkstra's 1959 algorithm and achieves better
performance (with respect to time) by using heuristics.
Takes in the ``start`` node and a ``goal`` node and returns the
shortest path between them as a list of nodes. Use pathCost() to find
the cost of traversing the path.
.. note::
Does not currently use the heuristic function, making it less
efficient than the bi-directional Dijkstra's algorithm used in
:func:`dijkstraBi`.
.. deprecated:: 0.5
Use :func:`shortestPath` instead.
.. seealso::
:func:`dijkstra`, :func:`dijkstraBi`
'''
# The set of nodes already evaluated
closedset = []
# The set of tentative nodes to be evaluated.
openset = [start]
# The map of navigated nodes.
came_from = {}
# Distance from start along optimal path.
g_score = {start: 0}
h_score = {start: self.heuristicEstimateOfDistance(start, goal)}
# The estimated total distance from start to goal through y.
f_score = PriorityQueue()
f_score.push(h_score[start], start)
while len(openset) != 0:
# the node in openset having the lowest f_score[] value
heur, x = f_score.pop()
if x == goal:
path = self.reconstructPath(came_from, goal)
#log.info("Path found of weight: %g" % self.pathCost(path))
#log.info("Path: %s" % path)
return path
try:
openset.remove(x)
except ValueError as e:
log.critical("Remove %s from the openset: %s" % (str(x), e))
raise
closedset.append(x)
for y in self.neighborNodes(x):
if y in closedset:
continue
if(exceptions is not None and (x,y) in exceptions):
costxy = float('infinity')
else:
costxy = self.timeBetween(x,y)
tentative_g_score = g_score[x] + costxy
if y not in openset:
openset.append(y)
tentative_is_better = True
elif tentative_g_score < g_score[y]:
tentative_is_better = True
else:
tentative_is_better = False
if tentative_is_better == True:
#log.debug("Update node %s's weight to %g" % (y,
#tentative_g_score))
came_from[y] = x
g_score[y] = tentative_g_score
h_score[y] = self.heuristicEstimateOfDistance(y, goal)
f_score.reprioritize(g_score[y] + h_score[y], y)
return None # Failure