0% found this document useful (0 votes)
8 views8 pages

Khushidsf 2

The document provides an implementation of a hash table using two methods for collision resolution: chaining and linear probing. It includes standard operations such as insert, find, delete, and display, with options for handling key replacements. The driver code allows user interaction to perform these operations on the hash table.

Uploaded by

rosiriw830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Khushidsf 2

The document provides an implementation of a hash table using two methods for collision resolution: chaining and linear probing. It includes standard operations such as insert, find, delete, and display, with options for handling key replacements. The driver code allows user interaction to perform these operations on the hash table.

Uploaded by

rosiriw830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 8

Khushi Soni (43)

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:

def __init__(self, size=10):

self.size = size

self.table = [[] for _ in range(self.size)] # Initialize each index as an empty list

def _hash(self, key):

"""Hash function to map keys to table indices."""

return hash(key) % self.size

def insert_with_replacement(self, key, value):

"""Insert key-value pair with replacement if key exists."""

index = self._hash(key)

# Check if the key exists and replace the value if found

for i, (k, v) in enumerate(self.table[index]):

if k == key:

self.table[index][i] = (key, value) # Replace the value

return

# If key doesn't exist, add it to the chain

self.table[index].append((key, value))
def insert_without_replacement(self, key, value):

"""Insert key-value pair without replacing existing values."""

index = self._hash(key)

# Check if the key already exists, don't insert if found

for k, v in self.table[index]:

if k == key:

return # Don't insert if the key exists

# If key doesn't exist, add it to the chain

self.table[index].append((key, value))

def find(self, key):

"""Find the value associated with a key."""

index = self._hash(key)

for k, v in self.table[index]:

if k == key:

return v

return None # Return None if key not found

def delete(self, key):

"""Delete a key-value pair."""

index = self._hash(key)

for i, (k, v) in enumerate(self.table[index]):

if k == key:

del self.table[index][i] # Delete the pair

return True

return False # Return False if the key wasn't found


def display(self):

"""Display the contents of the hash table."""

for i, chain in enumerate(self.table):

print(f"Index {i}: {chain}")

class HashTableLinearProbing:

def __init__(self, size=10):

self.size = size

self.table = [None] * self.size # Initialize the table with None

def _hash(self, key):

"""Hash function to map keys to table indices."""

return hash(key) % self.size

def _probe(self, key):

"""Linear probing to find the next available index."""

index = self._hash(key)

original_index = index

while self.table[index] is not None and self.table[index][0] != key:

index = (index + 1) % self.size # Probe the next 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):

"""Insert key-value pair with replacement if key exists (linear probing)."""

index = self._probe(key)

if index is None:

print("Error: Hash table is full!")

return

if self.table[index] is not None and self.table[index][0] == key:

self.table[index] = (key, value) # Replace existing key-value pair

else:

self.table[index] = (key, value) # Insert the new key-value pair

def insert_without_replacement(self, key, value):

"""Insert key-value pair without replacing existing values (linear probing)."""

index = self._probe(key)

if index is None:

print("Error: Hash table is full!")

return

if self.table[index] is None:

self.table[index] = (key, value) # Insert the new key-value pair

# If the slot is already filled with the same key, do nothing (no replacement)

def find(self, key):

"""Find the value associated with a key using linear probing."""

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

def delete(self, key):

"""Delete a key-value pair using linear probing."""

index = self._probe(key)

if index is None or self.table[index] is None or self.table[index][0] != key:

return False # Key not found

# Mark the slot as None and rehash the subsequent entries

self.table[index] = None

next_index = (index + 1) % self.size

while self.table[next_index] is not None:

rehash_key, rehash_value = self.table[next_index]

self.table[next_index] = None

self.insert_with_replacement(rehash_key, rehash_value) # Rehash the next entries

next_index = (next_index + 1) % self.size

return True

def display(self):

"""Display the contents of the hash table."""

for i, item in enumerate(self.table):

print(f"Index {i}: {item}")

# Driver Code (to interact with the user)

def main():

size = int(input("Enter size of hash table: "))


method = input("Choose method for collision resolution (chaining/linear probing):
").strip().lower()

operation = None

hash_table = None

if method == 'chaining':

hash_table = HashTableChaining(size)

elif method == 'linear probing':

hash_table = HashTableLinearProbing(size)

else:

print("Invalid method chosen.")

return

while True:

print("\nOperations: 1 - Insert, 2 - Find, 3 - Delete, 4 - Display, 5 - Exit")

operation = int(input("Choose operation: "))

if operation == 1:

key = input("Enter key: ")

value = input("Enter value: ")

replacement = input("With replacement? (yes/no): ").strip().lower() == 'yes'

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:

key = input("Enter key to find: ")

value = hash_table.find(key)

if value is None:

print(f"Key '{key}' not found.")

else:

print(f"Value for key '{key}': {value}")

elif operation == 3:

key = input("Enter key to delete: ")

if hash_table.delete(key):

print(f"Key '{key}' deleted successfully.")

else:

print(f"Key '{key}' not found.")

elif operation == 4:

hash_table.display()

elif operation == 5:

print("Exiting...")

break

else:

print("Invalid operation. Try again.")

if __name__ == "__main__":
main()

You might also like