Skip to content

Added doctest to heap.py #11129

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 2 commits into from
Nov 13, 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
32 changes: 31 additions & 1 deletion data_structures/heap/heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,37 @@ def __repr__(self) -> str:
return str(self.h)

def parent_index(self, child_idx: int) -> int | None:
"""return the parent index of given child"""
"""
returns the parent index based on the given child index

>>> h = Heap()
>>> h.build_max_heap([103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5])
Copy link
Member

@cclauss cclauss Nov 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's test with zero, negative integers, floating point numbers, and strings.

Let's test h.parent_index(12) which is NOT in the heap.

We want to test how the algorithm works but also how it fails when given bad input.

>>> h
[209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]

>>> h.parent_index(-1) # returns none if index is <=0

>>> h.parent_index(0) # returns none if index is <=0

>>> h.parent_index(1)
0
>>> h.parent_index(2)
0
>>> h.parent_index(3)
1
>>> h.parent_index(4)
1
>>> h.parent_index(5)
2
>>> h.parent_index(10.5)
4.0
>>> h.parent_index(209.0)
104.0
>>> h.parent_index("Test")
Traceback (most recent call last):
...
TypeError: '>' not supported between instances of 'str' and 'int'
"""
if child_idx > 0:
return (child_idx - 1) // 2
return None
Expand Down