本文整理汇总了Python中PriorityQueue.PriorityQueue.empty方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.empty方法的具体用法?Python PriorityQueue.empty怎么用?Python PriorityQueue.empty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PriorityQueue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.empty方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import empty [as 别名]
def search(self, startHex, goalHex):
startNode = HexNode(startHex, None)
goalNode = HexNode(goalHex, None)
frontier = PriorityQueue()
frontier.put(startNode, 0)
cameFrom = {}
currCost = {}
cameFrom[startNode] = None
currCost[startNode] = 0
while not frontier.empty():
currNode = frontier.get()
if currNode.h == goalNode.h:
break
for nextNode in self.getNeighborNodes(currNode.h):
newCost = currCost[currNode] + self.cost(currNode, nextNode)
if nextNode not in currCost or newCost < currCost[nextNode]:
currCost[nextNode] = newCost
priority = newCost + HexMap.heuristic(goalNode, nextNode)
frontier.put(nextNode, priority)
cameFrom[nextNode] = currNode
return cameFrom, currCost
示例2: a_star_search
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import empty [as 别名]
def a_star_search(self, start, goal):
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
cost_so_far = {}
came_from[start] = start
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()
if current.position_x == goal.position_x and current.position_y == goal.position_y:
break
for next in self.neighbors(current):
next_cell = Cell(next[0], next[1])
if next_cell.position_x == goal.position_x and next_cell.position_y == goal.position_y:
next_cell = goal
new_cost = cost_so_far[current] + self.heuristic(current, next_cell)
if next_cell not in cost_so_far or new_cost < cost_so_far[next_cell]:
cost_so_far[next_cell] = new_cost
priority = new_cost + self.heuristic(goal, next_cell)
frontier.put(next_cell, priority)
came_from[next_cell] = current
return came_from # , cost_so_far
示例3: test1
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import empty [as 别名]
def test1():
from PriorityQueue import PriorityQueue
import random
print("test1")
ITERATIONS = 10000
que = PriorityQueue()
heap = BinomialHeap()
length = 0
for i in range(ITERATIONS):
if i % 300 == 0:
print("Progress: {:.0%}".format(float(i) / ITERATIONS))
op = random.randint(0, 99)
if op < 1: # Clear
heap.check_structure()
for j in range(length):
if heap.dequeue() != que.extractMin():
raise AssertionError()
if not que.empty():
raise AssertionError()
length = 0
elif op < 2: # Peek
heap.check_structure()
if length > 0:
val = que.extractMin()
if heap.peek() != val:
raise AssertionError()
que.insert(val)
elif op < 60: # Add
n = random.randint(1, 100)
for j in range(n):
val = random.randint(0, 9999)
que.insert(val)
heap.enqueue(val)
length += n
elif op < 70: # Merge
n = random.randint(1, 100)
temp = BinomialHeap()
for j in range(n):
val = random.randint(0, 9999)
que.insert(val)
temp.enqueue(val)
heap.merge(temp)
if len(temp) != 0:
raise AssertionError()
length += n
elif op < 100: # Remove
n = min(random.randint(1, 100), length)
for j in range(n):
if heap.dequeue() != que.extractMin():
raise AssertionError()
length -= n
else:
raise AssertionError()
if len(heap) != length:
raise AssertionError()
print("Test passed")
示例4: __init__
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import empty [as 别名]
class Game:
""" Defines a running instance of a Murder Mystery.
Handles the initialization of the various game states.
"""
def __init__(self, abilities, players):
self.gm = players[0]
self.errorAbility = ErrorAbility()
self.eventQueue = PriorityQueue()
self.parser = Parser()
self.inbox = Inbox()
self.outbox = Outbox()
self.players = {}
for player in players[1:]:
self.players[player.getName().lower()] = player
self.abilities = {}
for ability in abilities:
self.abilities[ability.getName().lower()] = ability
def getGameMaster(self):
return self.gm
def addEvent(self, event):
""" Schedules an event to be run.
"""
self.eventQueue.put(event)
def addEvents(self, events):
""" Schedules a list of events to be run.
"""
if(events):
for event in events:
self.eventQueue.put(event)
def removeEvent(self, event):
""" Removes a specific event from the priority queue
"""
self.eventQueue.remove(event)
def getOutbox(self):
return self.outbox
def isValidAbility(self, name):
return name.lower() in self.abilities
def getAbility(self, name):
return self.abilities[name.lower()]
def getAbilityNames(self):
return self.abilities.keys()
def isValidPlayer(self, name):
return name.lower() in self.players
def getPlayer(self, name):
return self.players[name.lower()]
def getPlayerNames(self):
return self.players.keys()
def removePlayer(self, name):
if( self.isValidPlayer(name) ):
del self.players[name.lower()]
def run(self):
""" Run the game, and Don't stop.
Ever.
"""
print "Starting the main loop!"
while( True ):
self.step()
time.sleep(5)
def step(self):
""" Perform one step of the game logic.
You need to call this repeatedly to make the game run.
"""
#process incoming messages
newMessages = self.inbox.poll()
commands = self.parser.parse(self.abilities.values(), newMessages, self.errorAbility)
for (sender,ability,args) in commands:
print "Handling '"+ability.getName()+"' for '"+sender+"'"
for player in self.players.values():
if( player.getContact() == sender ):
print "\tRunning the ability!"
self.addEvents(ability.getEventsFor(self, player, args))
break
#Process the queue of events
while( not self.eventQueue.empty() ):
event = self.eventQueue.get()
if( event.when() < datetime.now() ):
print "Performing an event"
self.addEvents(event.perform(self))
else:
#Doesn't support peeking, so shove it back in the queue if it
#shouldn't happen yet
self.eventQueue.put(event)
break
示例5: PathFinder
# 需要导入模块: from PriorityQueue import PriorityQueue [as 别名]
# 或者: from PriorityQueue.PriorityQueue import empty [as 别名]
#.........这里部分代码省略.........
except:
print >> sys.stderr, 'Vertex not found in points'
return
# find the neighbors of this point
row = self.visibility_graph[index]
for i in range(0, len(row)):
neighbor = self.points[i]
if row[i] == 1 and neighbor not in self.visited:
if self.is_goal(neighbor):
# If this child is the goal node, we're done!
last_node = BFSNode(neighbor, current_node)
self.frontier.append(last_node)
self.search_snapshots.append(Snapshot(list(self.visited), list(self.frontier), uses_bfs_nodes=True))
self.reconstruct_path_from_last_node(last_node)
return
else:
# Add this child to the end of the queue
self.frontier.append(BFSNode(neighbor, current_node))
# If we get to this point, then the frontier became empty before we found the goal
print "BFS failed to find the goal"
def reconstruct_path_from_last_node(self, last_node):
self.path = []
node = last_node
while node:
self.path.insert(0, node.my_point)
node = node.parent
############################
### A-STAR ALGORITHM ###
############################
def get_a_star_path(self):
print "Running A* to Get Path"
self.a_star_search()
return self.path
def a_star_search(self):
self.clear_history()
self.frontier = PriorityQueue()
self.frontier.put(AStarNode(self.points[0], None, 0), 0)
last_node = None
# iterate until the frontier is empty
while not self.frontier.empty():
snapshot = Snapshot(list(self.visited), self.frontier.getNodes(), uses_a_star_nodes=True)
self.search_snapshots.append(snapshot)
current = self.frontier.get()
if current.my_point in self.visited:
# Never mind, we didn't want that snapshot :)
self.search_snapshots.remove(snapshot)
continue
self.visited.append(current.my_point)
# end immediately if the goal is found
if self.is_goal(current.my_point):
last_node = current
break
# find out which point we're dealing with
try:
index = self.points.index(current.my_point)
except:
print >> sys.stderr, 'Vertex not found in points'
return False
# prepare qualified new neighbors to be added to frontier
row = self.visibility_graph[index]
index = 0
for item in row:
neighbor = self.points[index]
if item == 1 and neighbor not in self.visited:
distance = current.cost
distance += self.distance(neighbor, current.my_point) # distance so far
est_distance_remaining = distance + self.distance(neighbor, self.points[1]) # est. distance to go
self.frontier.put(AStarNode(neighbor, current, distance), est_distance_remaining)
index += 1
# unwind path back to start
while not last_node == None:
self.path.insert(0, last_node.my_point)
last_node = last_node.parent
################################
### SEARCH ALGORITHM HELPERS ###
################################
def clear_history(self):
self.visited = []
self.frontier = []
self.path = []
self.search_snapshots = []
def is_goal(self, point):
return point == self.points[1] # the goal point is always the second one in our list of points
def distance(self, point1, point2):
return math.sqrt((point1[0]-point2[0])**2 + (point1[1] - point2[1]) ** 2)