Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random non-uniform distribution with given proportion

I have 3 labels: "A","B","C".

I want to generate a random list with 100 elements, 60% of them are "A", 30% are "B", 10% are "C".

How can I do this? (I am new in python, hope this question is not too silly.)


Edit: My question is slightly different from this question: Generate random numbers with a given (numerical) distribution

Just like in the comment, I want exactly 60% of them are "A", not every element has a 60% probability to be "A". So the numpy.random.choice() is not the solution for me.

like image 870
xirururu Avatar asked Mar 22 '15 01:03

xirururu


2 Answers

You can just permute a list. Lets say you create the list

x = list('A'*60 + 'B'*30 + 'C'*10)

Then, you can shuffle this in-place like so:

from random import shuffle
shuffle(x)
like image 170
ssm Avatar answered Oct 14 '22 03:10

ssm


If you want exactly 60% to be A, 30% B and 10% C and you know there have to be 100 elements in total, you can do something like the following:

import random

num = 100
prob_a = 0.6
prob_b = 0.3
prob_c = 0.1

As = int(num*prob_a) * 'A'
Bs = int(num*prob_b) * 'B'
Cs = int(num*prob_c) * 'C'

# create a list with 60 As, 30 Bs, and 10 Cs
chars = list(As + Bs + Cs)
random.shuffle(chars)

print("".join(chars))

That'll output something like BAAAAABBCBAABABAAAACAABBAABACAACBAACBBBAAACBAAAABAAABABAAAAABBBABAABAABAACCAABABAAAAAACABBBBCABAAAAA

like image 3
avacariu Avatar answered Oct 14 '22 03:10

avacariu