Heaps

Building heap was never been this easy. Follow these steps

  • First make a heap by importing Heap from AKDSFramework.

from AKDSFramework.structure import MaxHeap, MinHeap

Now let’s build a max heap with 15 random values.

mxheap = MaxHeap([data**2 for data in range(15)])

Now it’s important to call the build method on the heap to build the heap from an unstructed array of numbers. If the build is not done printing and doing operations on heap will not be valid and will generate HeapNotBuildError. So always build your heap with .heap() method if you caused any change in the heap structure. Each time calling .build() method will use O(logN) time.

mxheap.build()
# Now add few elements to the heap
mxheap.add(12)
mxheap.add(4)
# As the heap structure is changed so we have to call .build() again
mxheap.build()
print(mxheap)
[196, 100, 169, 64, 81, 144, 36, 49, 9, 1, 16, 121, 25, 4, 0, 12, 4]

This will return [2744, 1331, 2197, 729, 1000, 1728, 343, 512, 64, 8, 125, 1, 216, 27, 12, 4] and you also have the ability to see the heap printed prettyly by using prettyprint() method.

mxheap.prettyprint()
             Heap structure              
┏━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Node Value  left child  right child ┃
┡━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ 196                100          169 │
│ 100                 64           81 │
│ 169                144           36 │
│ 64                  49            9 │
│ 81                   1           16 │
│ 144                121           25 │
│ 36                   4            0 │
│ 49                  12            4 │
└────────────┴────────────┴─────────────┘

It’s important to call the build method on the heap to build the heap from an unstructed array of numbers. If the build is not done printing and doing operations on heap will not be valid and will generate HeapNotBuildError

mxheap.add(122)
mxheap.prettyprint()
---------------------------------------------------------------------------
HeapNotBuildError                         Traceback (most recent call last)
<ipython-input-7-adbfc79ce2a6> in <module>
----> 1 mxheap.prettyprint()

/usr/local/lib/python3.9/site-packages/AKDSFramework/structure/heap.py in prettyprint(self)
    120         else:
    121             notify("yeae", "mp3")
--> 122             raise HeapNotBuildError(
    123                 'The MaxHeap has not built yet or may have changed after a successful build, consider using the .build() method to build the heap first.')
    124 

HeapNotBuildError: The MaxHeap has not built yet or may have changed after a successful build, consider using the .build() method to build the heap first.