show me an example implementation of a division hash function
- User
show me an example implementation of a division hash function
- Assistant
A division hash function is a type of hash function that computes an index for a key by dividing the key by a prime number and taking the remainder. This method helps distribute keys uniformly across a hash table, reducing the likelihood of collisions.
Here's a simple implementation example in Python:
pythonclass HashTable: def __init__(self, size): # Initialize the hash table with a specified size self.size = size self.table = [None] * size def hash(self, key): # Simple division hash function # Use a prime number as the divisor for better distribution prime_number = 31 return key % prime_number % self.size def insert(self, key, value): # Insert a key-value pair into the hash table index = self.hash(key) # Handle collisions using linear probing while self.table[index] is not None: # If the key already exists, update the value if self.table[index][0] == key: self.table[index] = (key, value) return # If not, move to the next index index = (index + 1) % self.size # Store the new key-value pair self.table[index] = (key, value) def get(self, key): # Retrieve value by key index = self.hash(key) while self.table[index] is not None: if self.table[index][0] == key: return self.table[index][1] index = (index + 1) % self.size return None # Key not found def display(self): # Display the hash table for i, item in enumerate(self.table): if item is not None: print(f"Index {i}: Key {item[0]}, Value {item[1]}") else: print(f"Index {i}: Empty") # Example usage if __name__ == "__main__": # Create a hash table of size 10 hash_table = HashTable(10) # Insert some key-value pairs hash_table.insert(1, "Value 1") hash_table.insert(2, "Value 2") hash_table.insert(3, "Value 3") hash_table.insert(13, "Value 4") # This will cause a collision with key 3 # Retrieve values print(hash_table.get(2)) # Output: Value 2 print(hash_table.get(13)) # Output: Value 4 # Display the hash table hash_table.display()