Skip to content
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

Added doctest & docstring to quadratic_probing.py #10996

Merged
merged 3 commits into from
Oct 26, 2023
Merged
Changes from 2 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
39 changes: 39 additions & 0 deletions data_structures/hashing/quadratic_probing.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,39 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def _collision_resolution(self, key, data=None):
"""
Quadratic probing is an open addressing scheme used for resolving
collisions in hash table.

It works by taking the original hash index and adding successive
values of an arbitrary quadratic polynomial until open slot is found.

Hash + 1², Hash + 2², Hash + 3² .... Hash + n²

reference:
- https://en.wikipedia.org/wiki/Quadratic_probing
e.g:
1. Create hash table with size 7
>>> qp = QuadraticProbing(7)
>>> qp.insert_data(90)
>>> qp.insert_data(340)
>>> qp.insert_data(24)
>>> qp.insert_data(45)
>>> qp.insert_data(99)
>>> qp.insert_data(73)
>>> qp.insert_data(7)
>>> qp.keys()
{11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7}

2. Create hash table with size 8
>>> qp = QuadraticProbing(8)
>>> qp.insert_data(0)
>>> qp.insert_data(999)
>>> qp.insert_data(111)
>>> qp.keys()
{0: 0, 7: 999, 3: 111}
"""
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
"""
3. Try to add three data elements when only two were provisioned
>>> qp = QuadraticProbing(2)
>>> qp.insert_data(0)
>>> qp.insert_data(999)
>>> qp.insert_data(111)
???
"""

Copy link
Contributor Author

@Suyashd999 Suyashd999 Oct 26, 2023

Choose a reason for hiding this comment

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

@cclauss Done


i = 1
new_key = self.hash_function(key + i * i)

Expand All @@ -27,3 +60,9 @@ def _collision_resolution(self, key, data=None):
break

return new_key


if __name__ == "__main__":
import doctest

doctest.testmod()