[10]:
from typing import Dict
import uuid
from uhashring import HashRing
[11]:
def rnd_key() -> str:
    return uuid.uuid4().hex

def print_hist(counts: Dict[str, int]):
    total = sum(list(counts.values()))
    hist = {
        k: "%.2f %%" % (v / total * 100,)
        for k, v in counts.items()
    }
    print(hist)
[12]:
print("at begin, only two nodes")
hr = HashRing(nodes=["n1", "n2"])
counts = {"n1": 0, "n2": 0}
n_test = 1000
for _ in range(n_test):
    counts[hr.get_node(rnd_key())] += 1
print(f"test with {n_test} requests")
print_hist(counts)
at begin, only two nodes
test with 1000 requests
{'n1': '52.00 %', 'n2': '48.00 %'}
[13]:
print("add third node")
hr.add_node("n3")
counts = {"n1": 0, "n2": 0, "n3": 0}
for _ in range(n_test):
    counts[hr.get_node(rnd_key())] += 1
print(f"test with {n_test} requests")
print_hist(counts)

add third node
test with 1000 requests
{'n1': '33.00 %', 'n2': '32.40 %', 'n3': '34.60 %'}
[14]:
print("add fourth node")
hr.add_node("n4")
counts = {"n1": 0, "n2": 0, "n3": 0, "n4": 0}
for _ in range(n_test):
    counts[hr.get_node(rnd_key())] += 1
print(f"test with {n_test} requests")
print_hist(counts)

add fourth node
test with 1000 requests
{'n1': '25.50 %', 'n2': '24.00 %', 'n3': '25.10 %', 'n4': '25.40 %'}
[ ]: