Skip to content

Added doctest to heap.py #11059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 72 additions & 3 deletions data_structures/heap/heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ def right_child_idx(self, parent_idx: int) -> int | None:
def max_heapify(self, index: int) -> None:
"""
correct a single violation of the heap property in a subtree's root.

It is the function that is responsible for restoring the property
of Max heap i.e the maximum element is always at top.
"""
if index < self.heap_size:
violation: int = index
Expand All @@ -99,7 +102,29 @@ def max_heapify(self, index: int) -> None:
self.max_heapify(violation)

def build_max_heap(self, collection: Iterable[T]) -> None:
"""build max heap from an unsorted array"""
"""
build max heap from an unsorted array

>>> h = Heap()
>>> h.build_max_heap([20,40,50,20,10])
>>> h
[50, 40, 20, 20, 10]

>>> h = Heap()
>>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])
>>> h
[9, 8, 7, 4, 5, 6, 3, 2, 1, 0]

>>> h = Heap()
>>> h.build_max_heap([514,5,61,57,8,99,105])
>>> h
[514, 57, 105, 5, 8, 99, 61]

>>> h = Heap()
>>> h.build_max_heap([514,5,61.6,57,8,9.9,105])
>>> h
[514, 57, 105, 5, 8, 9.9, 61.6]
"""
self.h = list(collection)
self.heap_size = len(self.h)
if self.heap_size > 1:
Expand All @@ -108,7 +133,24 @@ def build_max_heap(self, collection: Iterable[T]) -> None:
self.max_heapify(i)

def extract_max(self) -> T:
"""get and remove max from heap"""
"""
get and remove max from heap

>>> h = Heap()
>>> h.build_max_heap([20,40,50,20,10])
>>> h.extract_max()
50

>>> h = Heap()
>>> h.build_max_heap([514,5,61,57,8,99,105])
>>> h.extract_max()
514

>>> h = Heap()
>>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])
>>> h.extract_max()
9
"""
if self.heap_size >= 2:
me = self.h[0]
self.h[0] = self.h.pop(-1)
Expand All @@ -122,7 +164,34 @@ def extract_max(self) -> T:
raise Exception("Empty heap")

def insert(self, value: T) -> None:
"""insert a new value into the max heap"""
"""
insert a new value into the max heap

>>> h = Heap()
>>> h.insert(10)
>>> h
[10]

>>> h = Heap()
>>> h.insert(10)
>>> h.insert(10)
>>> h
[10, 10]

>>> h = Heap()
>>> h.insert(10)
>>> h.insert(10.1)
>>> h
[10.1, 10]

>>> h = Heap()
>>> h.insert(0.1)
>>> h.insert(0)
>>> h.insert(9)
>>> h.insert(5)
>>> h
[9, 5, 0.1, 0]
"""
self.h.append(value)
idx = (self.heap_size - 1) // 2
self.heap_size += 1
Expand Down