random playing soundfiles according to rating.

JW John-Whitlock at ieee.org
Thu Feb 9 11:38:57 EST 2006


I think of it this way: you randomly pick a entry out of a dictionary,
then roll a 100-side die to see if the pick is "good enough".  Repeat
until you find one, or give up.

import random

def rand_weighted_pick(weighted_picks):
    for i in range(100):
        name, prob = random.choice(weighted_picks)
        if prob >= random.randint(0,100): return name
    # Give up and return a random choice
    return random.choice(weighted_picks)[0]

if __name__ == "__main__":
    test_vals = [("A",50),("B",30),("C",20)]
    dist = dict()
    for name, prob in test_vals: dist[name] = 0
    for x in xrange(1000): dist[rand_weighted_pick(test_vals)] += 1
    print "Expected: A = 500, B = 300, C = 200"
    print "Actual  : A = %d, B = %d, C = %d"%(dist['A'], dist['B'],
dist['C'])




More information about the Python-list mailing list