Skip to content

Commit fe4aad0

Browse files
authored
Added doctest & docstring to quadratic_probing.py (#10996)
* Added doctest & docstring to quadratic_probing.py * Update quadratic_probing.py * Update quadratic_probing.py
1 parent a8dfd40 commit fe4aad0

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

data_structures/hashing/quadratic_probing.py

+55
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,55 @@ def __init__(self, *args, **kwargs):
1212
super().__init__(*args, **kwargs)
1313

1414
def _collision_resolution(self, key, data=None):
15+
"""
16+
Quadratic probing is an open addressing scheme used for resolving
17+
collisions in hash table.
18+
19+
It works by taking the original hash index and adding successive
20+
values of an arbitrary quadratic polynomial until open slot is found.
21+
22+
Hash + 1², Hash + 2², Hash + 3² .... Hash + n²
23+
24+
reference:
25+
- https://en.wikipedia.org/wiki/Quadratic_probing
26+
e.g:
27+
1. Create hash table with size 7
28+
>>> qp = QuadraticProbing(7)
29+
>>> qp.insert_data(90)
30+
>>> qp.insert_data(340)
31+
>>> qp.insert_data(24)
32+
>>> qp.insert_data(45)
33+
>>> qp.insert_data(99)
34+
>>> qp.insert_data(73)
35+
>>> qp.insert_data(7)
36+
>>> qp.keys()
37+
{11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7}
38+
39+
2. Create hash table with size 8
40+
>>> qp = QuadraticProbing(8)
41+
>>> qp.insert_data(0)
42+
>>> qp.insert_data(999)
43+
>>> qp.insert_data(111)
44+
>>> qp.keys()
45+
{0: 0, 7: 999, 3: 111}
46+
47+
3. Try to add three data elements when the size is two
48+
>>> qp = QuadraticProbing(2)
49+
>>> qp.insert_data(0)
50+
>>> qp.insert_data(999)
51+
>>> qp.insert_data(111)
52+
>>> qp.keys()
53+
{0: 0, 4: 999, 1: 111}
54+
55+
4. Try to add three data elements when the size is one
56+
>>> qp = QuadraticProbing(1)
57+
>>> qp.insert_data(0)
58+
>>> qp.insert_data(999)
59+
>>> qp.insert_data(111)
60+
>>> qp.keys()
61+
{4: 999, 1: 111}
62+
"""
63+
1564
i = 1
1665
new_key = self.hash_function(key + i * i)
1766

@@ -27,3 +76,9 @@ def _collision_resolution(self, key, data=None):
2776
break
2877

2978
return new_key
79+
80+
81+
if __name__ == "__main__":
82+
import doctest
83+
84+
doctest.testmod()

0 commit comments

Comments
 (0)