Biased random?

Scott David Daniels daniels at dsl-only.net
Mon Aug 27 23:51:50 EDT 2007


Ivan Voras wrote:
> I have a list of items, and need to choose several elements from it,
> "almost random". The catch is that the elements from the beginning
> should have more chance of being selected than those at the end (how
> much more? I don't care how the "envelope" of probability looks like at
> this point - can be linear). I see that there are several functions in
> Python standard libraries for various distribution, but is there an easy
> pythonic way to make them do what I need?

import random

def choose(samples, **kwargs):
     total = sum(kwargs.values())
     result = []
     for n in range(samples):
	choice = random.random() * total
         for key, weight in kwargs.iteritems():
             choice -= weight
             if choice <= 0:
                 result.append(key)
                 total -= kwargs.pop(key)
                 break
         else:
             raise ValueError('Too many samples taken from the universe')
     return result

print choose(3, a=1, b=2, c=2, d=1, e=3)


-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list