Skip to content

Instantly share code, notes, and snippets.

@CalebCurry
Last active October 30, 2024 12:49
Show Gist options
  • Save CalebCurry/2d7c33a9ba59670d4da9c4e7bce36e4d to your computer and use it in GitHub Desktop.
Save CalebCurry/2d7c33a9ba59670d4da9c4e7bce36e4d to your computer and use it in GitHub Desktop.
import hashlib
def hash_key(key):
"""Returns an integer hash for a given key."""
# Use SHA-256 for consistency in hash values
hash_object = hashlib.sha256(key.encode())
return int(hash_object.hexdigest(), 16)
def distribute_keys(keys, servers):
"""Distributes keys across the given number of servers using hashing."""
for key in keys:
hash_value = hash_key(key)
last_five_digits = f"{hash_value % 100000:05}"
server = hash_value % servers
print(f"{key} - {last_five_digits} - Server {server}")
# Initial keys to hash
keys = [f"key{i}" for i in range(8)]
# First hash distribution with 4 servers
print("Initial distribution with 4 servers:")
distribute_keys(keys, 4)
# Simulate rehashing by running distribution with the same keys
print("\nRehashed distribution with 4 servers:")
distribute_keys(keys, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment