Overview
TheHashTable class provides a hash table data structure that maps keys to values. It uses separate chaining (linked lists) to handle hash collisions and provides O(1) average-case performance for insertions, deletions, and lookups.
Constructor
The initial capacity of the hashtable (number of buckets)
Attributes
The number of items currently stored in the hashtable
The total capacity (number of buckets) of the hashtable
Methods
hash_function
Compute a hash value for a given key.The key to convert to a hash value
Hash value modded to the hashtable capacity
set
Set a key-value pair in the hashtable. If the key exists, replace the value; otherwise, create a new key-value pair.The key to set or update
The value to associate with the key
get
Get the value associated with a given key.The key to look up
The value associated with the key, or
None if the key is not foundkey_exists
Check whether a key exists in the hashtable.The key to check for
True if the key exists, False otherwiseremove
Remove a key-value pair from the hashtable.The key to remove
KeyError if the key is not found in the hashtable
pop
Remove a key and return its value. If the key is not found, return a default value.The key to remove
The value to return if the key is not found
The value associated with the key, or the default value if not found
enumerate
Return an enumeration of key-value pairs in the hashtable.Enumeration of key-value pairs as
[key, value] listsshow_buckets
Return a string displaying the contents of all buckets in the hashtable.A string representation of all buckets and their contents
Special Methods
__len__
Return the number of items in the hashtable.__getitem__
Get a value using bracket notation.__setitem__
Set a value using bracket notation.__delitem__
Delete a key-value pair using thedel keyword.
__contains__
Check if a key exists using thein operator.
__iter__
Iterate over all keys in the hashtable.__eq__
Compare two hashtables for equality.__repr__
Return a string representation of the hashtable.Complete Example
Performance
-
Average Case:
- Insert: O(1)
- Lookup: O(1)
- Delete: O(1)
-
Worst Case:
- Insert: O(n) (all keys hash to same bucket)
- Lookup: O(n)
- Delete: O(n)
Notes
- The hashtable uses separate chaining to handle collisions
- Keys are converted to strings before hashing
- The hash function uses polynomial rolling hash with multiplier 31
- Default capacity is 20 buckets
- The hashtable does not automatically resize