Perleone
0
Q:

python heapq

>>> import heapq
>>> heap = []
>>> heapq.heappush(heap, (5, 'write code'))
>>> heapq.heappush(heap, (7, 'release product'))
>>> heapq.heappush(heap, (1, 'write spec'))
>>> heapq.heappush(heap, (3, 'create tests'))
>>> heapq.heappop(heap)#pops smallest
(1, 'write spec')
>>> heapq.nlargest(2,heap)#displays n largest values without popping
[(7, 'release product'),(5, 'write code')]
>>> heapq.nsmallest(2,heap)#displays n smallest values without popping
[(3, 'create tests'),(5, 'write code')]
>>> heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapq.heapify(heap)#converts a list to heap
>>> heap
[0, 1, 2, 6, 3, 5, 4, 7, 8, 9]
>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5
# Python code to demonstrate working of  
# heapify(), heappush() and heappop() 
  
# importing "heapq" to implement heap queue 
import heapq 
  
# initializing list 
li = [5, 7, 9, 1, 3] 
  
# using heapify to convert list into heap 
heapq.heapify(li) 
  
# printing created heap 
print ("The created heap is : ",end="") 
print (list(li)) 
  
# using heappush() to push elements into heap 
# pushes 4 
heapq.heappush(li,4) 
  
# printing modified heap 
print ("The modified heap after push is : ",end="") 
print (list(li)) 
  
# using heappop() to pop smallest element 
print ("The popped and smallest element is : ",end="") 
print (heapq.heappop(li)) 
-1

New to Communities?

Join the community