Search code examples
pythonrandomprobabilityprobability-distribution

How to tune random.choice probability - python -


I made a function that randomly selects one from a list of texts.

def ttc(*arg):
    a = random.choice([*arg])
    return ''.join(a)

print(ttc("Price", "Condition", "Loan"))
print(ttc("entertainment", "geese", "Uruguay", "comedy", "butterfly"))

But I found it necessary to make certain words have a higher probability of being selected.

For example, can we change the probability of being selected sequentially from the front of the list by 50% 30% 20% like this?


Solution

  • Basic way:

    Simply modify the input to reflect your probabilities

    ["a","b","c"] vs ["a","a","a","b","c"] # 3 times more "a" then "b" or "c"
    

    Provide probabilities:

    Use random.choices with a 1-element draw and provide a probability:

    import random
    
    # fixed - some unneeded stuff in here - no idea why ...
    def ttc(*arg):
        a = random.choice(arg)   # no need to list and unpack
        return a                 # no need to join here
    
    def ttc2(words, probs, draws = 1):
        a = random.choices(words, weights=probs, k = draws)
        return a if draws == 1 else ' '.join(a)
    
    for _ in range(5):
        print(ttc("Price", "Condition", "Loan"))
        # Price is roughly 20 times more likely
        # use [5,3,2] to get 50% 30% 20%
        # print 30 draws of that probability
        print( ttc2( ["Price", "Condition", "Loan"], [20,1,1], 30))
    

    Output:

    Loan
    Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Condition Price Price Price Price Price Price Loan Price Price Price Price Price
    
    Price
    Price Price Price Price Price Price Price Condition Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Condition Price Price Price Price
    
    Price
    Price Price Price Price Price Price Price Price Price Price Price Price Loan Price Price Condition Price Price Price Price Price Price Price Price Price Price Price Price Condition Price
    
    Condition
    Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Condition Price Loan Price Price Price Price Price Price Price Price Price Price
    
    Loan
    Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Price Condition Price Price Price