本文整理汇总了Python中queue.PriorityQueue.put方法的典型用法代码示例。如果您正苦于以下问题:Python PriorityQueue.put方法的具体用法?Python PriorityQueue.put怎么用?Python PriorityQueue.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类queue.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Background
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
class Background(object):
def __init__(self, slave_count=1):
self.slave_count = slave_count
self.slaves = []
self.jobs = PriorityQueue()
def start(self):
for i in range(self.slave_count):
t = Thread(target=self._run, daemon=True)
t.start()
self.slaves.append(t)
def stop(self):
self.jobs.join()
def _run(self):
while True:
job = self.jobs.get()[-1]
try:
job()
except Exception as e:
logging.exception(e)
finally:
self.jobs.task_done()
def action(self, job, rank=0):
self.jobs.put((rank, datetime.utcnow(), str(uuid4()), job))
def function(self, job, callback, rank=0):
@wraps(job)
def inner():
self.action(partial(callback, job()), rank=rank)
return self.action(inner, rank=rank)
示例2: test_starts_actions_and_adds_back_to_queue
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def test_starts_actions_and_adds_back_to_queue(self):
# given
start_time = 0
deadline = 10
action_to_start = Action(start_time, deadline+1)
action_to_start.agent = Mock(name="agent")
action_to_start.is_applicable = Mock(return_val=True)
action_to_start.apply = Mock(name="apply")
model = Mock(name="model")
execution_queue = PriorityQueue()
execution_queue.put(ActionState(action_to_start, start_time, ExecutionState.pre_start))
# when
actual, _stalled = simulator.execute_action_queue(model, execution_queue,
break_on_new_knowledge=False, deadline=deadline)
# then
assert_that(execution_queue.queue, has_length(1))
time, state, action = execution_queue.queue[0]
assert_that(time, equal_to(action_to_start.end_time))
assert_that(state, equal_to(ExecutionState.executing))
assert_that(action, equal_to(action_to_start))
assert_that(actual.executed, is_(empty()))
assert_that(is_not(action_to_start.apply.called))
assert_that(actual.simulation_time, equal_to(start_time))
示例3: heuristic_map_constructor
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def heuristic_map_constructor(goal, cost_map, resolution=0.2):
"""construct heuristic query map
goal - State, has x,y attributes
return type : matrix has same size as cost_map
"""
if type(goal)==list or type(goal)==tuple:
g_i, g_j = floor(goal[1]/resolution), floor(goal[0]/resolution)
else:
g_i, g_j = floor(goal.y/resolution), floor(goal.x/resolution)
goal_grid = Grid(g_i, g_j, cost_map[g_i, g_j])
grid_dict = {(goal_grid.i, goal_grid.j):goal_grid}
pq = PriorityQueue()
pq.put(goal_grid)
heuristic_map = np.inf*np.ones(cost_map.shape)
while not pq.empty():
current = pq.get()
successors = current.successors(grid_dict)
for successor in successors:
successor.extend = True
cost = current.cost + resolution*(abs(current.i-successor.i)+abs(current.j-successor.j)) + cost_map[successor.i, successor.j]
if successor.cost > cost:
successor.cost = cost
heuristic_map[successor.i, successor.j] = cost
pq.put(successor)
return heuristic_map
示例4: bestFirstSearch
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def bestFirstSearch(self, startNode, goalNode, heuristic):
bestFitstQueue = PriorityQueue(0)
visitedNode = {}
parent = {}
utility = Utility()
goalNodeStateDict = utility.getGoalNodeStateDict(goalNode)
bestFitstQueue.put((1, startNode))
while not(bestFitstQueue.empty()):
poppedTuple = bestFitstQueue.get()
self.nodesVisited+=1
popped = poppedTuple[1]
if (popped == goalNode):
# print popped==goalNode
return self.backtrack(popped)
else:
visitedNode[popped.stringRep]=popped
if self.maxDepth < popped.level:
self.maxDepth = popped.level
popped.expand()
for child in popped.children:
if child.stringRep not in visitedNode:
heuristicOfChild = utility.getHeuristic(child, goalNode, heuristic, goalNodeStateDict)
bestFitstQueue.put((heuristicOfChild, child))
self.maxQueueSize +=1
示例5: create_tree
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def create_tree(to_comprime_text):
separated_chars = Counter(to_comprime_text)
nodes = {}
for char in separated_chars:
nodes[char] = Node(separated_chars[char], char)
q = PriorityQueue()
for node in nodes:
q.put((nodes[node].get_node_value(), node))
while q.qsize() > 1:
left = q.get()
right = q.get()
nodes[left[1]].set_binary_node_value(0)
nodes[right[1]].set_binary_node_value(1)
node_representation = nodes[left[1]].get_node_representation() + nodes[right[1]].get_node_representation()
node_value = nodes[left[1]].get_node_value() + nodes[right[1]].get_node_value()
nodes[node_representation] = Node(node_value, node_representation)
nodes[node_representation].set_left_node(nodes[left[1]])
nodes[node_representation].set_right_node(nodes[right[1]])
nodes[left[1]].set_back_node(nodes[node_representation])
nodes[right[1]].set_back_node(nodes[node_representation])
q.put((nodes[node_representation].get_node_value(), node_representation))
return nodes
示例6: EventQueue
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
class EventQueue(object):
def __init__(self):
"""Event queue for executing events at
specific timepoints.
In current form it is NOT thread safe."""
self.q = PriorityQueue()
def schedule(self, f, ts):
"""Schedule f to be execute at time ts"""
self.q.put(EqItem(ts, f))
def schedule_recurring(self, f, interval):
"""Schedule f to be run every interval seconds.
It will be run for the first time interval seconds
from now"""
def recuring_f():
f()
self.schedule(recuring_f, time.time() + interval)
self.schedule(recuring_f, time.time() + interval)
def run(self):
"""Execute events in the queue as timely as possible."""
while True:
event = self.q.get()
event.f()
示例7: run_test_1
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def run_test_1():
pq = PriorityQueue()
pq.put( (12, 'doze'))
pq.put( (10, 'dez') )
pq.put( (11, 'onze'))
while( not pq.empty() ):
print(pq.get(), end= ' ')
示例8: get_discrete_voronoi_diagram
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def get_discrete_voronoi_diagram(image, list_of_generators):
"""
Given an image and a list of generating points, return the discrete voronoi diagram. The DVD is represented
by a matrix of numbers, with each number being a different color(section) of the DVD
:param image: The image being stippled
:param list_of_generators: A list of generating points
:return: The discrete voronoi diagram
"""
width, length = image.size
discrete_voronoi_diagram = [[-1 for x in range(width)] for y in range(length)]
queue = PriorityQueue()
for i in range(len(list_of_generators)):
if 0 <= list_of_generators[i][0] <= width and 0 <= list_of_generators[i][1] <= length:
queue.put((0, list_of_generators[i], i))
while not queue.empty():
triple = queue.get()
point_coordinate = triple[1]
x_coor = point_coordinate[0]
y_coor = point_coordinate[1]
i = triple[2]
if discrete_voronoi_diagram[y_coor][x_coor] == -1:
discrete_voronoi_diagram[y_coor][x_coor] = i
neighboring_points = [(x_coor, y_coor+1), (x_coor+1, y_coor), (x_coor, y_coor-1), (x_coor-1, y_coor)]
for item in neighboring_points:
if 0 <= item[0] < width and 0 <= item[1] < length:
if discrete_voronoi_diagram[item[1]][item[0]] == -1:
distance = math.sqrt((item[0] - list_of_generators[i][0])**2 +
(item[1] - list_of_generators[i][1])**2)
queue.put((distance, item, i))
return discrete_voronoi_diagram
示例9: findPathAux
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def findPathAux(self, startPoint, endPoint):
def reachable(point, mapping):
x,y = point
if x >=0 and y>=0 and y<len(mapping) and x< len(mapping[y]):
return mapping[y][x]
return False
reached = set()
unchecked = PriorityQueue()
moves = {(i,j) for i in [-1,0,1] for j in [-1,0,1]}
moves.remove((0,0))
count=0
unchecked.put((0,startPoint,[]))
while not unchecked.empty():
_, point, seq = unchecked.get()
count+=1
if point == endPoint:
print(count)
return seq
if not point in reached:
reached.add(point)
for move in moves:
pointNew = pairPlus(point, move)
if reachable(pointNew, self.terrainGrid):
seqNew = seqPlus(seq, move)
unchecked.put((dist(pointNew, endPoint), pointNew, seqNew))
示例10: _test_loaded_in_correct_order
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def _test_loaded_in_correct_order(
self, enrichment_manager: EnrichmentManager, enrichment_loaders: Iterable[EnrichmentLoader]
):
"""
Tests that the given enrichment manager applies enrichments defined be the given loaders in the correct order.
:param enrichment_manager: enrichment manager
:param enrichment_loaders: enrichment loaders
"""
logging.root.setLevel(logging.CRITICAL)
cookie = Cookie("the_identifier")
enrichment_loaders_priority_queue = PriorityQueue()
for enrichment_loader in enrichment_loaders:
if enrichment_loader.can_enrich(cookie):
enrichment_loaders_priority_queue.put(enrichment_loader)
enrichment = enrichment_manager.next_enrichment(cookie)
while enrichment is not None:
expected_enrichment_loader = enrichment_loaders_priority_queue.get() # type: EnrichmentLoader
expected_enrichment = expected_enrichment_loader.load_enrichment(cookie)
self.assertEqual(enrichment, expected_enrichment)
cookie.enrich(enrichment)
expected_enrichment_loader.can_enrich = MagicMock(return_value=False)
enrichment = enrichment_manager.next_enrichment(cookie)
self.assertTrue(enrichment_loaders_priority_queue.empty())
示例11: solve_q1
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def solve_q1(text):
from queue import PriorityQueue
freq = dict()
for i in text:
if i not in freq:
freq[i] = 0
freq[i] += 1
q = PriorityQueue()
for i in freq:
n = HuffmanNode()
n.f = freq[i]
n.c = i
q.put(n)
while q.qsize() > 1:
a = q.get()
b = q.get()
c = HuffmanNode()
c.f = a.f + b.f
c.l = a
c.r = b
q.put(c)
root = q.get()
ret = 0
for i in freq:
ret += freq[i] * root.get(i)
print(ret)
示例12: giveConclusion
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def giveConclusion():
foodmap = mapFood()
print("Foodmap =", foodmap)
heatmap = mapHeat()
foodheat = {}
foods = PriorityQueue()
for (food, distance) in foodmap:
foodheat[food] = heatmap[food[1]][food[0]]
if foodheat[food] < calculateLimit(heatmap):
foods.put((distance, food))
if not foods.empty():
good_food = foods.get()[1]
head = snakes[speler_nummer].head
path = givePath(head, good_food)
direction = giveDirection(path[0], path[1])
else:
minimum = wall_value
direction = -1
head = snakes[speler_nummer].head
backuplist = []
for coordinate in neighbours(head):
if heatmap[coordinate[1]][coordinate[0]] < minimum:
direction = giveDirection(head, coordinate)
minimum = heatmap[coordinate[1]][coordinate[0]]
elif level[coordinate[1]][coordinate[0]] in ['.','x']:
backuplist.append(coordinate)
if direction == -1:
if len(backuplist)!= 0:
direction = giveDirection(head,backuplist[0])
else:
print("Goodbye, cruel world!")
direction = 'r'
return direction
示例13: astar
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def astar(start, env):
#frontier_inserstions zählt die Operationen, frontier_max_size die größte vorkommende Frontier
frontier_insertions = 1
frontier_max_size = 1
start.cost = 0
frontier = PriorityQueue()
frontier.put((0, start))
while frontier.qsize() != 0 :
node = frontier.get()[1]
#print("Visiting node " + node.name)
#print("\n".join(["".join(node.status() for node in line) for line in env]))
#Frontier erweitern, hierbei nur solche Knoten aufnehmen, die besucht werden dürfen (kein X) und noch nie in der Frontier waren
#(ansonsten wäre cost gesetzt)
for neighbour in node.neighbours:
if neighbour.cost is None and not neighbour.blocked:
neighbour.prev = node
neighbour.cost = node.cost + 1
frontier.put(( neighbour.cost + neighbour.h , neighbour))
frontier_insertions += 1
if frontier_max_size < frontier.qsize():
frontier_max_size = frontier.qsize()
if neighbour.goal:
print("Time: {} Memory: {}".format(frontier_insertions, frontier_max_size))
return neighbour
print("Time: {} Memory: {}".format(frontier_insertions, frontier_max_size))
示例14: AStarAlgorithm
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
class AStarAlgorithm(object):
def __init__(self, start, goal):
self.path = []
self.visitedQueue = []
self.PriorityQueue = PriorityQueue()
self.start = start
self.goal = goal
def Solve(self):
startState = StateString(self.start, 0, self.start, self.goal)
count = 0
self.PriorityQueue.put((0, count, startState))
while(not self.path and sel.PriorityQueue.qsize()):
closestChild = self.PriorityQueue.get()[2]
closestChild.GenerateChildren()
slef.visitedQueue.append(closestChild.value)
for child in closestChild.children:
if child.value not in self.visitedQueue:
count += 1
if not child.distance:
self.path = child.path
break
self.PriorityQueue.put((child.distance, count, child))
if not self.path:
print ("Goal of " + self.goal + "is not possible")
return self.path
示例15: max_spanning_tree
# 需要导入模块: from queue import PriorityQueue [as 别名]
# 或者: from queue.PriorityQueue import put [as 别名]
def max_spanning_tree(self):
"""
Kruskal's algorithm for min spanning tree, to get most important
connections in graph.
-> Graph
"""
# TODO: Test
# TODO: Add unit tests
# TODO: FIx bug, use disjoint set during the test of connection
pq = PriorityQueue()
for conn in self.get_connections():
# Hack negative number used to get use priority queue in inverse order
# (to get max values first)
pq.put((-self.get_connection_weight(conn), self.connection_key(conn)))
min_tree = Graph()
while not pq.empty():
curr_weight, curr_connection = pq.get()
curr_weight = -curr_weight # Hack with negative number
if min_tree.is_node_in_graph(curr_connection[0]) and \
min_tree.is_node_in_graph(curr_connection[1]):
continue
min_tree.add_connection(*curr_connection)
min_tree.set_connection_weight(curr_connection, curr_weight)
for node in self.get_nodes():
min_tree.set_node_weight(node, self.get_node_weight(node))
return min_tree