Te damos la bienvenida a nuestra comunidad, en este sitio hallarás la solucíon a lo que andabas buscando.
Ejemplo 1: cola de prioridad de Python
from queue import PriorityQueue
classPqElement(object):def__init__(self, value:int):
self.val = value
#Custom Compare Function (less than or equsal)def__lt__(self, other):"""self < obj."""return self.val > other.val
#Print each element functiondef__repr__(self):returnf'PQE:self.val'#Usage-
pq = PriorityQueue()
pq.put(PqElement(v))#Add Item - O(Log(n))
topValue = pq.get()#Pop top item - O(1)
topValue = pq.queue[0].val #Get top value - O(1)
Ejemplo 2: cola de prioridad de Python
classPriorityQueueSet(object):"""
Combined priority queue and set data structure.
Acts like a priority queue, except that its items are guaranteed to be
unique. Provides O(1) membership test, O(log N) insertion and O(log N)
removal of the smallest item.
Important: the items of this data structure must be both comparable and
hashable (i.e. must implement __cmp__ and __hash__). This is true of
Python's built-in objects, but you should implement those methods if you
want to use the data structure for custom objects.
"""def__init__(self, items=[]):"""
Create a new PriorityQueueSet.
Arguments:
items (list): An initial item list - it can be unsorted and
non-unique. The data structure will be created in O(N).
"""
self.set=dict((item,True)for item in items)
self.heap = self.set.keys()
heapq.heapify(self.heap)defhas_item(self, item):"""Check if ``item`` exists in the queue."""return item in self.setdefpop_smallest(self):"""Remove and return the smallest item from the queue."""
smallest = heapq.heappop(self.heap)del self.set[smallest]return smallest
defadd(self, item):"""Add ``item`` to the queue if doesn't already exist."""if item notin self.set:
self.set[item]=True
heapq.heappush(self.heap, item)
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)