Python - How To Weighted Random Choices in Python

ID : 513

viewed : 241

Tags : PythonPython RandomPython Weighted Random

vote vote

98

Selecting a set of random values from a list of elements or a string is easy.

But integrating probabilities to it or weights makes this task a bit more complex. These can be termed as weighted choices.

In this tutorial, we will learn how to perform weighted random choices in Python.

Weighted Random Choices in Python

We can use the random module, an in-built Python module, to perform a weighted random choice of elements from a list of elements or objects.

This module has a function choices(), that returns a k sized list of elements from a list of elements or a string. This function has the following arguments.

  • population: A list of elements or a string from which random elements will be chosen.
  • weights: A list of weights for all the elements of a list of elements and characters of a string.
  • k: The size of the output list of elements.

Now that we are through with the theory, let us understand how to perform weighted random choices practically. Refer to the following Python code for this.

import random  data = ["Q", "W", "E", "R", "T", "Y"] prob = [0.1, 0.1, 0.3, 0.25, 0.25, 0.0] x = random.choices(     population = data,     weights = prob,     k = 25 ) print(x) 

Output:

['R', 'W', 'T', 'E', 'Q', 'R', 'Q', 'Q', 'R', 'E', 'R', 'R', 'T', 'E', 'T', 'W', 'R', 'T', 'R', 'E', 'T', 'E', 'R', 'Q', 'R'] 

From the output, we can access that there is no Y because it has a probability or weight of 0.0. Other values, Q, W, E, R, and T, can be found in the output because they have non-zero probabilities or weights.

Let us look at an example dealing with a string of characters. Refer to the following Python code for this.

import random  data = "QWERTY" prob = [0.1, 0.1, 0.3, 0.25, 0.25, 0.0] x = random.choices(     population = data,     weights = prob,     k = 25 ) print(x) 

Output:

['E', 'R', 'R', 'E', 'T', 'T', 'E', 'R', 'Q', 'R', 'R', 'R', 'E', 'Q', 'T', 'R', 'E', 'R', 'E', 'T', 'T', 'T', 'Q', 'R', 'T'] 

Like the output of the last Python code snippet, it doesn’t have the Y character because it has a probability of 0.0.

  • Related HOW TO?