- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Heap Queue Algorithm
The heap data structures can be used to represents a priority queue. In python it is available into the heapq module. Here it creates a min-heap. So when the priority is 1, it represents the highest priority. When new elements are inserted, the heap structure updates.
To use this module, we should import it using −
import heapq
There are some heap related operations. These are −
Method heapq.heapify(iterable)
It is used to convert an iterable dataset to heap data structure.
Method heapq.heappush(heap, element)
This method is used to insert the element into the heap. After that re-heap the entire heap structure.
Method heapq.heappop(heap)
This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements.
Method heapq.heappushpop(heap, element)
This method is used to insert and pop element in one statement..
Method heapq.heapreplace(heap, element)
This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap.
Method heapq.nlargest(n, iterable, key=None)
This method is used to return n largest element from the heap.
Method heapq.nsmallest(n, iterable, key=None)
This method is used to return n smallest element from the heap.
Example Code
import heapq my_list = [58, 41, 12, 17, 89, 65, 23, 20, 10, 16, 17, 19] heapq.heapify(my_list) print(my_list) heapq.heappush(my_list, 7) print(my_list) print('Popped Element: ' + str(heapq.heappop(my_list))) print(my_list) new_iter = list() new_iter = heapq.nlargest(4, my_list) print(new_iter)
Output
[10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65] [7, 16, 10, 17, 17, 12, 23, 20, 41, 89, 58, 65, 19] Popped Element: 7 [10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65] [89, 65, 58, 41]
- Related Articles
- Heap queue (or heapq) in Python
- What is Heap queue (or heapq) in Python?
- Stack and Queue in Python using queue Module
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
- Python Program for Heap Sort
- Is Max Heap in Python?
- Program to check heap is forming max heap or not in Python
- BFS using vectors & queue as per the algorithm of CLRS in C Program?
- What is Heap Sort in Python?
- Multithreaded Priority Queue in Python
- Program to Implement Queue in Python
- Python Array Bisection Algorithm
- How to Implement Priority Queue in Python?
- How to implement Multithreaded queue With Python
- Check if a queue can be sorted into another queue using a stack in Python
