2

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

1

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I was going to post this answer only
Shouldn't there be a colon at the end of the elif line?
pk = (0.8, 0.15, 0.05) or your variant?
You're right. Fixed. The doc says "(xk, pk) where xk are integers with non-zero probabilities pk with sum(pk) = 1."
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.