1>>> import heapq
2>>> heap = []
3>>> heapq.heappush(heap, (5, 'write code'))
4>>> heapq.heappush(heap, (7, 'release product'))
5>>> heapq.heappush(heap, (1, 'write spec'))
6>>> heapq.heappush(heap, (3, 'create tests'))
7>>> heapq.heappop(heap)#pops smallest
8(1, 'write spec')
9>>> heapq.nlargest(2,heap)#displays n largest values without popping
10[(7, 'release product'),(5, 'write code')]
11>>> heapq.nsmallest(2,heap)#displays n smallest values without popping
12[(3, 'create tests'),(5, 'write code')]
13>>> heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
14>>> heapq.heapify(heap)#converts a list to heap
15>>> heap
16[0, 1, 2, 6, 3, 5, 4, 7, 8, 9]
17>>> def heapsort(iterable):
18... h = []
19... for value in iterable:
20... heappush(h, value)
21... return [heappop(h) for i in range(len(h))]
22...
23>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
24[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
25
1from queue import PriorityQueue
2
3class PqElement(object):
4 def __init__(self, value: int):
5 self.val = value
6
7 #Custom Compare Function (less than or equsal)
8 def __lt__(self, other):
9 """self < obj."""
10 return self.val > other.val #Compare Function For Max Heap - Max element on top
11
12 #Print each element function
13 def __repr__(self):
14 return f'PQE:{self.val}'
15
16#Usage-
17pq = PriorityQueue()
18pq.put(PqElement(v)) # Add Item - O(Log(n))
19topValue = pq.get() # Pop top item - O(1)
20topValue = pq.queue[0].val # Get top value - O(1)
21pqSize = pq.qsize() # Provide Queue Size - O(1)
22isEmpty = pq.empty() # Is PQ is empty
1from queue import PriorityQueue
2
3class PqElement(object):
4 def __init__(self, value: int):
5 self.val = value
6
7 #Custom Compare Function (less than or equsal)
8 def __lt__(self, other):
9 """self < obj."""
10 return self.val > other.val
11
12 #Print each element function
13 def __repr__(self):
14 return f'PQE:{self.val}'
15
16#Usage-
17pq = PriorityQueue()
18pq.put(PqElement(v)) #Add Item - O(Log(n))
19topValue = pq.get() #Pop top item - O(1)
20topValue = pq.queue[0].val #Get top value - O(1)