graded randomness

Tim Chase python.list at tim.thechases.com
Fri Dec 28 08:23:39 EST 2018


On 2018-12-28 16:15, Abdur-Rahmaan Janhangeer wrote:
> greetings,
> 
> let us say that i have a box of 5 balls,
> 
> green balls - 2 with probability 2/5
> red balls 2 - with probability 2/5
> blue balls 1 - with probability 1/5
> 
> how to program the selection so that the random choices reflect the
> probabilities?

You're looking for what are called "weighted choices" which the
random.choice() function provides as of Py3.6

https://docs.python.org/3/library/random.html#random.choices

>>> from random import choices
>>> distribution = {"green":2, "red": 2, "blue", 1}
>>> data, weights = zip(*distribution.items())
>>> sum(weights)
5
>>> sorted(choices(data, weights=weights, k=20))
['blue', 'blue', 'blue', 'blue', 'green', 'green', 'green', 'green',
'green', 'green', 'green', 'green', 'red', 'red', 'red', 'red',
'red', 'red', 'red', 'red']

-tim






More information about the Python-list mailing list