The before code randomly assigns load without control, causing imbalance. The after code shows three split strategies: equal split divides load evenly with remainder handling; exact split assigns fixed amounts per target with validation; percentage split allocates load based on given ratios, handling rounding by assigning remainder to last target.
### Before: naive random split without control
import random
def naive_split(targets, load):
distribution = {t: 0 for t in targets}
for _ in range(load):
chosen = random.choice(targets)
distribution[chosen] += 1
return distribution
### After: implementing equal, exact, and percentage split strategies
def equal_split(targets, load):
base = load // len(targets)
remainder = load % len(targets)
distribution = {t: base for t in targets}
for i in range(remainder):
distribution[targets[i]] += 1
return distribution
def exact_split(targets, exact_allocations):
# exact_allocations is dict {target: exact_load}
total = sum(exact_allocations.values())
distribution = {t: exact_allocations.get(t, 0) for t in targets}
if total != sum(distribution.values()):
raise ValueError("Exact allocations sum mismatch")
return distribution
def percentage_split(targets, percentages, load):
# percentages is dict {target: percent_float} summing to 1.0
distribution = {}
allocated = 0
for t in targets[:-1]:
count = int(load * percentages.get(t, 0))
distribution[t] = count
allocated += count
distribution[targets[-1]] = load - allocated # assign remainder
return distribution