Skip to content

Instantly share code, notes, and snippets.

@lucemia
Last active December 27, 2015 17:59
Show Gist options
  • Save lucemia/7366507 to your computer and use it in GitHub Desktop.
Save lucemia/7366507 to your computer and use it in GitHub Desktop.
python order with prob
import random
x = ['x', 2]
y = ['y', 3]
z = ['z', 4]
SAMPLES = 100000
choices = [x,y,z]
total_weight = float(sum([k[1] for k in choices]))
vs = []
for i in range(SAMPLES):
choices.sort(key=lambda i: random.random())
choices.sort(key=lambda i: random.random() > i[1] / total_weight)
vs.append([k[0] for k in choices])
print 'target distribution'
print x[1] / total_weight, y[1] / total_weight, z[1] / total_weight
print 'test distribution'
print len([k for k in vs if k[0] == 'x']) / float(SAMPLES),
print len([k for k in vs if k[0] == 'y']) / float(SAMPLES),
print len([k for k in vs if k[0] == 'z']) / float(SAMPLES)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment