com um clique
build-priority-queue
// For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue.
// For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue.
Conducts iterative deep research on any topic using web search, progressive exploration, and structured synthesis. Use when asked for comprehensive research, deep investigation, thorough analysis, or multi-source exploration of any topic. Triggers: research, investigate, deep dive, comprehensive analysis, explore thoroughly, find everything about.
For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers.
For performance work: measure before changing, profile to find bottlenecks, compare before and after.
For symbolic computation: ASTs, mathematical expressions, code that manipulates code structure, expression transformations.
For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work.
For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context.
| name | build-priority-queue |
| description | For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue. |
Use heapq for O(log n) push/pop of minimum element.
import heapq
# Basic usage
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
heapq.heappop(heap) # Returns 1 (minimum)
# With tuples for priority ordering
tasks = []
heapq.heappush(tasks, (priority, task_id, task_data))
_, _, task = heapq.heappop(tasks)
# heapify existing list
data = [3, 1, 4, 1, 5]
heapq.heapify(data) # In-place, O(n)
import heapq
class PriorityQueue:
"""A queue where the item with minimum key is always popped first."""
def __init__(self, items=(), key=lambda x: x):
self.key = key
self.items = [] # Heap of (score, item) pairs
for item in items:
self.add(item)
def add(self, item):
"""Add item to the queue."""
pair = (self.key(item), item)
heapq.heappush(self.items, pair)
def pop(self):
"""Pop and return the item with minimum key."""
return heapq.heappop(self.items)[1]
def top(self):
"""Peek at minimum item without removing."""
return self.items[0][1]
def __len__(self):
return len(self.items)
# Usage in A* search
def astar_search(problem, h):
frontier = PriorityQueue([Node(problem.initial)],
key=lambda n: n.path_cost + h(n))
while frontier:
node = frontier.pop()
if problem.is_goal(node.state):
return node
for child in expand(problem, node):
frontier.add(child)
return None
(priority, tiebreaker, data) for stable ordering