[Tutor] weighted choices from among many lists
kevin parks
kp8 at mac.com
Sat Mar 11 07:38:03 CET 2006
I have several lists... and i would like to some times chose from one
list and for a while choose from a different list, etc... so i cooked
this up and it almost works so that i can get colors 50% of the time,
doggies 25%, beer 10%, and guitars 100% (if i was real smart i would
make my index thingy check to make sure my wieghets added up to 100% or
scaled them to be..... ) ... meanwhile, as you can see i am 90% of the
way there, can anyone figure out what i got wrong or suggest
improvements to the code...
best,
-kevin--
#!/usr/bin/env python
import random
def windex(lst):
'''a random.choose() function that makes weighted choices
accepts a list of tuples with the item and probability as a pair
like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
>>> y=windex(x)'''
n = random.uniform(0, 1)
for item, weight in lst:
if n < weight:
break
n = n - weight
return item
def test():
lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow',
'black', 'white' ]
lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer',
'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund',
'Doberman', 'Greyhound', 'Pug', 'Spaniel']
lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout']
lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro',
'gretsch', 'martin', 'ibanez']
x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)]
i = 1
while i < 100:
lst = windex(x)
print i, lst,
pick = random.choice(lst)
print pick
i = i + 1
if __name__ == "__main__":
test()
More information about the Tutor
mailing list