Search code examples
pythonrandomprobability

Increasing / decrasing chance on random module


For example I am programming a game . I need some money . Chests is free but keys is paid . How can I increase the chance of key needed premium chest and how can I decrase the chance of fully free premium chest

import random 

list1 = ["fully free premium chest", "key needed premium chest", "fully free normal chest"]


random.choice(list1)

Solution

  • Use random.choices and give weights to your different options, proportional to the probability you want to give to each of them.

    Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

    If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

    For example, you could use the weights [10, 40, 2] to give the second item a larger probability to be chosen, and a small one for the last item.

    It would be:

    import random 
    
    list1 = ["fully free premium chest", "key needed premium chest", "fully free normal chest"]
    
    
    random.choices(list1, weights=[10, 40, 2], k=1)[0]
    # 'key needed premium chest'