2

How to generate random sequence of 1, 2, 3 provided that 80 % of numbers will 1, 15 % will 2 and 5 % will 3?

Kenenbek Arzymatov
  • 8,439
  • 19
  • 58
  • 109
  • Possibly related to http://stackoverflow.com/questions/4276787/python-selecting-numbers-with-associated-probabilities, http://stackoverflow.com/questions/2073235/random-weighted-choice, http://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution – Jérôme May 13 '16 at 14:38

2 Answers2

8

Use random to get a random number in [0,1) and map your outputs to that interval.

from random import random

result = []

# Return 100 results (for instance)
for i in range(100):

    res = random()

    if res < 0.8:
        result.append(1)
    elif res < 0.95:
        result.append(2)
    else:
        result.append(3)

return result

This is a trivial solution. You may want to write a more elegant one that allows you to specify the probabilities for each number in a dedicated structure (list, dict,...) rather than in a if/else statement.

But then you might be better off using a dedicated library, as suggested in this answer. Here's an example with scipy's stats.rv_discrete

from scipy import stats
xk = np.arange(1, 4)
pk = (0.8, 0.15, 0.05)
custm = stats.rv_discrete(name='custm', values=(xk, pk))
# Return 100 results (for instance)
return custm.rvs(size=100)
Community
  • 1
  • 1
Jérôme
  • 13,328
  • 7
  • 56
  • 106
1

This should do the trick

import random

sequence = []

desired_length = n # how many numbers you want
for i in range(desired_length):
    random_value = random.random()
    if random_value < .8:
        sequence.append(1)
    elif random_value < .95:
        sequence.append(2)
    else:
        sequence.append(3)

print sequence
dayofthepenguin
  • 139
  • 1
  • 6