Настроение: | contemplative |
Entry tags: | computing |
ChatGPT
necax claims there is a shorter algorithm to sample from a population, but ChatGPT comes with exactly the same algorithm I invented, which it calls "cumulative summing method":
https://chatgpt.com/share/67236748-da18-800d-bcd1-a7bf2ba9d23c
It is completely equivalent to my
list.outcome = $find(s~+=?0; p~^(Me{?0}.z*)<<s~).1
method, except that it produces a list of K samples, instead of just one.
import random
def custom_choices(population, weights, k=1):
cumulative_weights = []
total = 0
# Build cumulative weights
for weight in weights:
total += weight
cumulative_weights.append(total)
# Generate samples
samples = []
for _ in range(k):
rand = random.uniform(0, total)
for item, cum_weight in zip(population, cumulative_weights):
if rand < cum_weight:
samples.append(item)
break
return samples
# Test it with your distribution
population = ['short', 'mid', 'long', 'bald']
weights = [70, 20, 5, 5]
samples = custom_choices(population, weights, k=10)
print(samples)