Roma Karageorgievich - 1 year ago 113

Python Question

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

Answer Source

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)
```