Heap using Python

Fig-Input

Implementation of Heap:

In python, the heapq module is used to implement a heap data structure. Mainly this module represents the min-heap type.

  • let’s take the input as [6,8,9,2,4].
  • Heapify function converts the input into the min-heap structure.
  • Add element “5” in heap structure using heappush function.
  • By using heappop, we can remove the smallest element from the heap.
  • Heapify function converts the input into the min-heap structure [3,4,9,8,6].
  • Heappushpop function adds an element “2” and deletes the smallest element in heap structure “2”.
  • Heapify function converts the input into the min-heap structure [3,4,9,8,6].
  • Heapreplace function deletes the smallest element first “2” and adds a new element “2”. Here the poped element is “3”.
  • Heapify function converts the input into the min-heap structure [3,4,9,8,6].
  • nsmallest(2, input) function returns the two smallest elements [3,4].
  • Heapify function converts the input into the min-heap structure [3,4,9,8,6].
  • nlargest(2, input) function returns the two largest elements [9,8].

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store