Khushidsf 2
Khushidsf 2
Q. Implement all the functions of a dictionary (ADT) using hashing and handle collisions using
chaining with / without replacement. Data: Set of (key, value) pairs, Keys are mapped to values,
Keys must be comparable, Keys must be unique. Standard Operations: Insert (key, value),
Find(key), Delete(key)
class HashTableChaining:
self.size = size
index = self._hash(key)
if k == key:
return
self.table[index].append((key, value))
def insert_without_replacement(self, key, value):
index = self._hash(key)
for k, v in self.table[index]:
if k == key:
self.table[index].append((key, value))
index = self._hash(key)
for k, v in self.table[index]:
if k == key:
return v
index = self._hash(key)
if k == key:
return True
class HashTableLinearProbing:
self.size = size
index = self._hash(key)
original_index = index
if index == original_index: # If we've looped back to the start, the table is full
return None
return index
def insert_with_replacement(self, key, value):
index = self._probe(key)
if index is None:
return
else:
index = self._probe(key)
if index is None:
return
if self.table[index] is None:
# If the slot is already filled with the same key, do nothing (no replacement)
index = self._probe(key)
if index is not None and self.table[index] is not None and self.table[index][0] == key:
return self.table[index][1]
return None # Return None if key is not found
index = self._probe(key)
self.table[index] = None
self.table[next_index] = None
return True
def display(self):
def main():
operation = None
hash_table = None
if method == 'chaining':
hash_table = HashTableChaining(size)
hash_table = HashTableLinearProbing(size)
else:
return
while True:
if operation == 1:
if replacement:
if method == 'chaining':
hash_table.insert_with_replacement(key, value)
else:
hash_table.insert_with_replacement(key, value)
else:
if method == 'chaining':
hash_table.insert_without_replacement(key, value)
else:
hash_table.insert_without_replacement(key, value)
elif operation == 2:
value = hash_table.find(key)
if value is None:
else:
elif operation == 3:
if hash_table.delete(key):
else:
elif operation == 4:
hash_table.display()
elif operation == 5:
print("Exiting...")
break
else:
if __name__ == "__main__":
main()