DSA 02
class HashNode:
def init(self, key, value):
self.key = key
self.value = value
self.next = None
class DictionaryADT:
def init(self, capacity=10):
self.capacity = capacity
self.table = [None] * self.capacity
def _hash_function(self, key):
"""Compute the hash index for a given key."""
return hash(key) % self.capacity
def insert(self, key, value):
index = self._hash_function(key)
head = self.table[index]
# Check if key exists; if yes, update it
while head:
if head.key == key:
head.value = value
print(f"Updated: ({key}, {value})")
return
head = head.next
# Otherwise, insert new node at the beginning of the chain
new_node = HashNode(key, value)
new_node.next = self.table[index]
self.table[index] = new_node
print(f"Inserted: ({key}, {value})")
def find(self, key):
index = self._hash_function(key)
head = self.table[index]
while head:
if head.key == key:
return head.value
head = head.next
return "Key not found"
def delete(self, key):
index = self._hash_function(key)
head = self.table[index]
prev = None
while head:
if head.key == key:
if prev:
prev.next = head.next
else:
self.table[index] = head.next
print(f"Deleted key: {key}")
return
prev = head
head = head.next
print("Key not found")
def display(self):
print("Current Dictionary State:")
for i, node in enumerate(self.table):
print(f"Bucket {i}:", end="")
while node:
print(f"({node.key}, {node.value})", end=" -> ")
node = node.next
print("None")
-------------------------------
Driver Code
-------------------------------
d = DictionaryADT()
Insert entries
d.insert("Alice", "555-1234")
d.insert("Bob", "555-5678")
d.insert("Charlie", "555-9999")
Update existing key
d.insert("Alice", "555-0000")
Find entries
print("Find Charlie:", d.find("Charlie"))
print("Find Eve:", d.find("Eve"))
Delete entries
d.delete("Bob")
d.delete("Eve") # Try deleting non-existing key
Display the final state
d.display()