Skip to content

Instantly share code, notes, and snippets.

@lucemia
Created November 8, 2013 14:45
Show Gist options
  • Save lucemia/7371993 to your computer and use it in GitHub Desktop.
Save lucemia/7371993 to your computer and use it in GitHub Desktop.
a correct version of weighted rank via sort
import random
SAMPLES = 10000
NUM = 5
options = [(k, random.randint(0, 100)) for k in range(NUM)]
choices = list(options)
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) for k in range(NUM)])
# if choices[0][0] == 'x':
vs.append([k[0] for k in choices])
# print vs
print 'target distribution'
for c in options:
print c[1] / total_weight,
print
print 'test distribution'
for c in options:
print len([k for k in vs if k[0] == c[0]]) / float(SAMPLES),
print
kk = options[0][0]
sub_total_weight = float(sum([k[1] for k in choices[1:]]))
for c in options[1:]:
print c[1] / sub_total_weight,
print
for c in options[1:]:
print len([k for k in vs if k[1] == c[0] and k[0] == kk]) / float(len([k for k in vs if k[0] == kk])),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment