Last active
October 30, 2024 12:49
-
-
Save CalebCurry/2d7c33a9ba59670d4da9c4e7bce36e4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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