Skip to content

Instantly share code, notes, and snippets.

@simonw
Created March 18, 2010 13:47
Show Gist options
  • Save simonw/336362 to your computer and use it in GitHub Desktop.
Save simonw/336362 to your computer and use it in GitHub Desktop.
Given a list of scores, returns the index of one of those items at random, biased towards the items with the highest scores.
"""
Given a list of scores, returns the index of one of those items at random,
biased towards the items with the highest scores.
e.g. random_index_with_bias([84, 62, 61, 67, 45])
To show it works, run it 1,000,000 times:
>>> scores = {}
>>> for i in range(1000000):
... r = random_index_with_bias([84, 62, 61, 67, 45])
... scores[r] = scores.get(r, 0) + 1
>>> scores
{0: 263421, 1: 193768, 2: 191029, 3: 210212, 4: 141570}
"""
import random
def random_index_with_bias(bias_scores):
rand = random.uniform(0, sum(bias_scores))
total = 0
for i, score in enumerate(bias_scores):
total += score
if rand <= total:
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment