Change language

Heap queue (or heapq) in Python

|

Heap operations:

1. heapify (iterable) : — this function is used to convert an iterable to a heap data structure. those. in heap order.

2. heappush (heap, ele) : — This function is used to insert an element mentioned in its arguments into the heap.  Order is adjusted so that heap structure is preserved .

3. heappop (heap) : — this function is used to remove and return the smallest element from the heap.  The order is adjusted so that heap structure is preserved .

# Python code to demonstrate how it works
# heapify (), heappush () and heappop ()

 
# import & quot; heapq & quot; to implement a heap queue

import heapq

 
# initializing list

li = [ 5 , 7 , 9 , 1 , 3 ]

 
# using heapify to heap the list
heapq.heapify (li)

 
# print the generated heap

print ( " The created h eap is: " , end = " ")

print ( list (li))

 
# using heappush () to inserting elements into the heap
# pushes 4

heapq.heappush (li, 4 )

 
# printing the modified heap

print ( "The modified heap after push is:" , end = "")

print ( list (li))

 
# using heappop ( ) display the smallest element

print ( " The popped and smallest element is: " , end = " ")

print (heapq.heappop (li))

Output:

 The created heap is: [1, 3, 9, 7 , 5] The modified heap after push is: [1, 3, 4, 7, 5, 9] The popped and smallest element is: 1 

4. heappushpop (heap, ele) : — This function combines the functionality of the push and pop operations in a single statement, increasing efficiency. Heap order is preserved after this operation.

5. heapreplace (heap, ele) : — This function also inserts and inserts an element in one statement, but it is different from the function above. When doing this, the element is fetched first, and then the — push.ie, a value greater than push may be returned.

# Python code to demonstrate how it works
# heappushpop () and heapreplce ()

 
# import & quot; heapq & quot; to implement a heap queue

import heapq

 
# list 1 initialization

li1 = [ 5 , 7 , 9 , 4 , 3 ]

  
# initialize list 2

li2 = [ 5 , 7 , 9 , 4 , 3 ]

 
# using heapify () to heap the list
heapq .heapify (li1)
heapq.heapify (li2)

  
# using heappushpop () to bump and fetch items
# claps 2

print ( "The popped item using heappushpop () is:" , end = "")

print (heapq.heappushpop (li1, 2 ))

 
# using heapreplace () to bump and fetch elements
# claps 3

print ( " The popped item using heapreplace () is: " , end = "")

print (heapq.heapreplace (li2, 2 ))

Output:

 The popped item using heappushpop ( ) is: 2 The popped item using heapreplace () is: 3 

6. nlargest (k, iterable, key = fun) : — This function is used to return the k largest elements from the specified iterable and match the key, if mentioned.

7. nsmallest (k, iterable, key = fun) : — This function is used to return the k smallest elements from the specified iterable and match the key, if mentioned.

# Python code to demonstrate how it works
# nlargest () and nsmallest ()

 
# import & quot; heapq & quot; to implement a heap queue

import heapq

 
# initializing list

li1 = [ 6 , 7 , 9 , 4 , 3 , 5 , 8 , 10 , 1 ]

 
# using heapify () to transform the list heap
heap q.heapify (li1)

 
# using the largest to print 3 largest numbers
# prints 10, 9 and 8

print ( "The 3 largest numbers in list are:" , end = "")

print (heapq.nlargest ( 3 , li1))

 
# using nsmallest to print the 3 smallest numbers
# prints 1, 3 and 4

print ( " The 3 smallest numbers in list are: " , end = "")

print (heapq.nsmallest ( 3 , li1))

Output:

 The 3 largest numbers in list are: [10, 9, 8] The 3 smallest numbers in list are: [1, 3 , 4] 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically