Hash Table Data Structure
A hash table is a data structure used to store key-value pairs, where the keys are hashed to map to a specific index in an array. It provides constant-time average case performance for insert, delete, and search operations.
python
# Hash Table class
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
self.table = [[] for _ in range(capacity)]
def hash_function(self, key):
return hash(key) % self.capacity
def insert(self, key, value):
index = self.hash_function(key)
for item in self.table[index]:
if item[0] == key:
item[1] = value
return
self.table[index].append((key, value))
def get(self, key):
index = self.hash_function(key)
for item in self.table[index]:
if item[0] == key:
return item[1]
raise KeyError(key)
def remove(self, key):
index = self.hash_function(key)
for i, item in enumerate(self.table[index]):
if item[0] == key:
del self.table[index][i]
return
raise KeyError(key)
No comments:
Post a Comment