jeudi 15 décembre 2016

Python: select random item from weighted list

Let's say I have two lists:

A = [('a', 'b'), ('b','c'), ('d', 'g' )]
B = [('x', 'z'), ('p','q')]

Each list will be given different weight to get selected for different conditions.

How to select an item from those weighted lists, if a condition is fulfilled? For example,

If condition1 is fulfilled, 
then the probability to select item on list A = 0.7,
then randomly select item in A

else 
randomly select item on B

This is the best I can do:

        def update_decision (decision):
            if condition :
                condition = condition
                return
                decision()

        def decision(A,B):
            A = [('a', 'b'), ('b','c'), ('d', 'g' )]
            B = [('x', 'z'), ('p','q')]
            if condition 1:
                return
                prob_need(0.8, A, B)

            elif condition 2:
                return
                prob_need(0.4, A, B)

            else:
                return
                prob_need(0.6, A, B)

        def prob_choice (probability,A, B):
             if random.random() <= probability :
                return
                decision = random.choice(A)
            else:
                return
                decision= random.choice(B)

I got this Particularly for prob_choice, it seems not right because I have to create a random probability, while in my case the probability is given.

Any help would be very appreciated




Aucun commentaire:

Enregistrer un commentaire