Expert Answer
Anonymous
class HashTable:
def __init__(self, size=10):
"""Initialize the hash table with a specified size."""
self.size = size
self.table = [[] for _ in range(self.size)] # Create a list of empty buckets
def _hash(self, key):
"""Hash the key to obtain an index."""
return hash(key) % self.size
def insert(self, key, value):
"""Insert a key-value pair into the hash table."""
index = self._hash(key)
for i, (k, v) in enumerate(self.table[index]):
if k == key: # Update the value if the key already exists
self.table[index][i] = (key, value)
return
self.table[index].append((key, value)) # Add a new key-value pair
def get(self, key):
"""Retrieve the value associated with a given key."""
index = self._hash(key)
for k, v in self.table[index]:
if k == key:
return v # Return the value if the key is found
return None # Return None if the key is not found
def remove(self, key):
"""Remove a key-value pair from the hash table."""
index = self._hash(key)
for i, (k, v) in enumerate(self.table[index]):
if k == key:
del self.table[index][i] # Remove the key-value pair
return True # Indicate successful removal
return False # Indicate that the key was not found
def __repr__(self):
"""String representation of the hash table."""
return "{ " + ", ".join(f"{k}: {v}" for bucket in self.table for k, v in bucket) + " }"
# Example usage
hash_table = HashTable()
hash_table.insert("name", "Alice")
hash_table.insert("age", 30)
hash_table.insert("city", "New York")
print(hash_table) # Output: { name: Alice, age: 30, city: New York }
print(hash_table.get("name")) # Output: Alice
print(hash_table.get("age")) # Output: 30
hash_table.remove("city")
print(hash_table) # Output: { name: Alice, age: 30 }