how to choose element from list based on probabilities?

Mel Wilson mwilson at the-wire.com
Mon Nov 17 04:21:03 CET 2003


In article <slrnbr81e4.gp0.mwilson at overlook.homelinux.net>,
Matthew Wilson <mwilson at sarcastic-horse.com> wrote:
>I have a list of very simple circle objects:
>
>class Circle:
>    def __init__(self, x,y,r):
>        self.center =(x,y)
>        self.r = r
>
>I want to write a function that accepts a list of circle objects and
>then chooses one of the circles and returns that circle.  The circles
>with the biggest areas should be the most likely to be chosen, but there
>should be some randomness.
>
>Subsequent calls to the function should not return the same circle.

Given a list of objects and probability weights:

    things = [(o1,p1), (o2,p2), (o3,p3), (o4,p4), (o5,p5)]

    accum = 0
    for o, p in things:
        accum += p
        if accum * random.random() < p:
            selected = o


   At the end the probability of any one of the things being
selected is equal to that things probablity weight divided
by the sum of all the weights.

   The way to meet the non-duplication requirement is to
remove the object from the working list when it's selected.
Keep track of each candiates index through the selection loop
if you need to.

        Regards.        Mel.




More information about the Python-list mailing list