本文整理汇总了Python中heapq.heappop方法的典型用法代码示例。如果您正苦于以下问题:Python heapq.heappop方法的具体用法?Python heapq.heappop怎么用?Python heapq.heappop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类heapq
的用法示例。
在下文中一共展示了heapq.heappop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: unload
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def unload(self, execute=True):
commands = CommandList()
undoWork = ConfigObject.prioritizeConfigs(self.currentConfig.values())
heapq.heapify(undoWork)
while undoWork:
prio, config = heapq.heappop(undoWork)
commands.extend(config.revert(self.currentConfig))
# Finally, execute the commands.
if execute and self.execCommands:
self.execute(commands)
self.previousCommands = commands
self.currentConfig = dict()
return True
示例2: getNextTodo
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def getNextTodo(self):
"""
Like an iterator function, it returns each element in the list of plans in order.
Returns:
(function, args) : Each todo is returned just how the user first added it
None : None is returned when there are no more todo's
"""
if len(self.workingPlans) == 0:
return None
else:
prio, todo, abt = heapq.heappop(self.workingPlans)
self.maxPriorityReturned = prio
# After popping the next plan, check if this is a skipped function.
# If so, then get the next plan.
if todo.func in self.skipFunctions:
return self.getNextTodo()
else:
self.abortPlans.append(abt)
return (todo.func, todo.args)
示例3: dijkstra
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def dijkstra(graph):
seen = set() # élément traités
d = {0: 0} # distance map
p = {} # path map
worklist = [(0, 0)] # worklist d'éléments à traiter (distance, id)
while worklist: # tant qu'il reste des éléments dans la worklist à traiter
dx, x_id = heappop(worklist) # distance, and id
if x_id in seen: # si l'élément est déjà traité on continue
continue
seen.add(x_id) # l'ajoute aux éléments traités
for w, y in graph[x_id]: # itère successeurs du noeud traité
if y in seen: # si le succ à déjà été traité continue
continue
dy = dx + w # pondération du succ
if y not in d or d[y] > dy: # si succ n'est pas encore referencé ou new distance < alors update
d[y] = dy # met à jour la distance pour succ dans la distance map
heappush(worklist, (dy, y)) # met le succ dans la worklist (avec sa pondération)
p[y] = x_id # met à jour le prédecesseur le plus court pour succ
# TODO: Do something with orphan BB
return p
示例4: finalize
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def finalize(self):
if self.ct < 1:
return
elif self.ct == 1:
return 0
total = ct = 0
dtp = None
while self.heap:
if total == 0:
if dtp is None:
dtp = heapq.heappop(self.heap)
continue
dt = heapq.heappop(self.heap)
diff = dt - dtp
ct += 1
total += total_seconds(diff)
dtp = dt
return float(total) / ct
示例5: search
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def search(state, goal_state, fn):
"""Best-first search"""
queue = []
entrance = 0
node = Node(state)
while not node.is_goal(goal_state):
node.expand()
for child in node.children:
queue_item = (fn(child), entrance, child)
heapq.heappush(queue, queue_item)
entrance += 1
node = heapq.heappop(queue)[2]
output = []
output.append(node.state)
for parent in node.parents():
output.append(parent.state)
output.reverse()
return output
示例6: post_processing
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def post_processing(self, score, epoch, model):
if self.freeze_model:
return
checkpoints_history_path = Path(
self.checkpoints_history_folder,
'{}_epoch{}.pth'.format(self.calculation_name, epoch)
)
torch.save(self.get_state_dict(model), checkpoints_history_path)
heapq.heappush(self.score_heap, (score, checkpoints_history_path))
if len(self.score_heap) > self.checkpoints_topk:
_, removing_checkpoint_path = heapq.heappop(self.score_heap)
removing_checkpoint_path.unlink()
self.logger.info('Removed checkpoint is {}'.format(removing_checkpoint_path))
if score > self.best_score:
self.best_score = score
self.best_epoch = epoch
torch.save(self.get_state_dict(model), self.best_checkpoint_path)
self.logger.info('best model: {} epoch - {:.5}'.format(epoch, score))
if self.scheduler.__class__.__name__ == 'ReduceLROnPlateau':
self.scheduler.step(score)
else:
self.scheduler.step()
示例7: _loop_and_run_scheduled_events
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def _loop_and_run_scheduled_events(self):
with self._work_ready_condition:
while not self._quit_event.is_set():
now = time.time()
while self._queue and self._queue[0].eta <= now:
event = heapq.heappop(self._queue)
if not event.cancelled:
# Only remove uncancelled events because when an Event is cancelled,
# its entry in _key_to_events is replaced with the replacement
# Event.
if event.key:
del self._key_to_events[event.key]
self._work_ready_condition.release()
self._thread_pool.submit(event.run)
self._work_ready_condition.acquire()
now = time.time()
if self._queue:
self._work_ready_condition.wait(self._queue[0].eta - now)
else:
self._work_ready_condition.wait()
示例8: merge
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def merge(lists):
merged_list = []
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
while heap:
#print(heap)
val, list_ind, element_ind = heapq.heappop(heap)
merged_list.append(val)
if element_ind + 1 < len(lists[list_ind]):
next_tuple = (lists[list_ind][element_ind + 1],
list_ind,
element_ind + 1)
heapq.heappush(heap, next_tuple)
return merged_list
#Test Cases
示例9: calculate_distances
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('inf') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
visit = [False for vertex in graph]
visit[starting_vertex] = True
while len(pq) > 0:
# print (pq)
current_distance, current_vertex = heapq.heappop(pq)
visit[current_vertex] = True
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
# Only consider this new path if it's better than any path we've already found.
if not visit[neighbor] and distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return sorted(distances.items())
示例10: calculate_distances
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('inf') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
visited = 0
visit = [False] * len(graph)
while len(pq) > 0:
if visited == len(graph):
break
# print (pq)
current_distance, current_vertex = heapq.heappop(pq)
if not visit[current_vertex]:
visit[current_vertex] = True
visited += 1
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if not visit[neighbor] and distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
示例11: __lt__
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def __lt__(self, other_node):
"""Comparison for priority queue.
Nodes with high gain are higher priority than nodes with low gain.
heapq.heappush only need the '<' operator.
heapq.heappop take the smallest item first (smaller is higher
priority).
Parameters
-----------
other_node : TreeNode
The node to compare with.
"""
if self.split_info is None or other_node.split_info is None:
raise ValueError("Cannot compare nodes with split_info")
return self.split_info.gain > other_node.split_info.gain
示例12: __pool_main
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def __pool_main(self, mesh_index):
mesh = self.__meshes[mesh_index]
queue = self.__build_queue(self.__fe[mesh_index, :, :mesh.edges_count], mesh.edges_count)
# recycle = []
# last_queue_len = len(queue)
last_count = mesh.edges_count + 1
mask = np.ones(mesh.edges_count, dtype=np.bool)
edge_groups = MeshUnion(mesh.edges_count, self.__fe.device)
while mesh.edges_count > self.__out_target:
value, edge_id = heappop(queue)
edge_id = int(edge_id)
if mask[edge_id]:
self.__pool_edge(mesh, edge_id, mask, edge_groups)
mesh.clean(mask, edge_groups)
fe = edge_groups.rebuild_features(self.__fe[mesh_index], mask, self.__out_target)
self.__updated_fe[mesh_index] = fe
示例13: get_skyline
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def get_skyline(lrh):
"""
Wortst Time Complexity: O(NlogN)
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
skyline, live = [], []
i, n = 0, len(lrh)
while i < n or live:
if not live or i < n and lrh[i][0] <= -live[0][1]:
x = lrh[i][0]
while i < n and lrh[i][0] == x:
heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))
i += 1
else:
x = -live[0][1]
while live and -live[0][1] <= x:
heapq.heappop(live)
height = len(live) and -live[0][0]
if not skyline or height != skyline[-1][1]:
skyline += [x, height],
return skyline
示例14: run
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def run(self):
self.__running = True
while self.__running:
self.__signal.acquire()
if not self.__jobs:
self.__signal.wait()
else:
now = datetime.datetime.now()
while (self.__jobs[0] < now):
job = heapq.heappop(self.__jobs)
action = job()
if action is not False:
self.__runner(action)
heapq.heappush(self.__jobs, job)
logging.getLogger("scheduler").debug("Sleeping %s seconds", (self.__jobs[0] - now))
self.__signal.wait((self.__jobs[0] - now).total_seconds())
self.__signal.release()
示例15: run_until_complete
# 需要导入模块: import heapq [as 别名]
# 或者: from heapq import heappop [as 别名]
def run_until_complete(self):
# Start all the coroutines.
for coro in self._new:
wait_for = coro.send(None)
heapq.heappush(self._waiting, Task(wait_for, coro))
# Keep running until there is no more work to do.
while self._waiting:
now = datetime.datetime.now()
# Get the coroutine with the soonest resumption time.
task = heapq.heappop(self._waiting)
if now < task.waiting_until:
# We're ahead of schedule; wait until it's time to resume.
delta = task.waiting_until - now
time.sleep(delta.total_seconds())
now = datetime.datetime.now()
try:
# It's time to resume the coroutine.
wait_until = task.coro.send(now)
heapq.heappush(self._waiting, Task(wait_until, task.coro))
except StopIteration:
# The coroutine is done.
pass