This project is part of the freeCodeCamp Python Certification.
It implements a basic hash table data structure. The application stores key-value pairs, handles collisions internally, and provides efficient methods for adding, retrieving, and removing data.
- Store key-value pairs using a custom hash function
- Convert string keys into numeric hash values
- Handle collisions using nested dictionaries (bucket system)
- Add new elements to the hash table
- Retrieve values by key (lookup)
- Remove elements by key
- Return None when a key is not found
- Python 3
-
You should define a class named
HashTablewith acollectionattribute initialized to an empty dictionary when a new instance ofHashTableis created. Thecollectiondictionary should store key-value pairs based on the hashed value of the key. -
The
HashTableclass should have four instance methods:hash,add,remove, andlookup. -
The
hashmethod should:- Take a string as a parameter.
- Return a hashed value computed as the sum of the Unicode (ASCII) values of each character in the string. You can use the
ordfunction for this computation.
-
The
addmethod should:- Take two arguments representing a key-value pair, and compute the hash of the key.
- Use the computed hash value as a key to store a dictionary containing the key-value pair inside the
collectiondictionary. - If multiple keys produce the same hash value, their key-value pairs should be stored in the existing nested dictionary under the same hash value.
-
The
removemethod should:- Take a key as its argument and compute its hash.
- Confirm if the key exists in the collection.
- Remove the corresponding key-value pair from the hash table.
- If the key does not exist in the collection, it should not raise an error or remove anything.
-
The
lookupmethod should:- Take a key as its argument.
- Compute the hash of the key, and return the corresponding value stored inside the hash table.
- If the key does not exist in the collection, it should return
None.
Example test cases are included as commented lines at the bottom of main.py.
Uncomment them to run and see the output.
- This project was developed to meet the certification requirements.
- The implementation focuses on correctness and clarity rather than extended functionality.