graded randomness

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


On 2018-12-28 17:31, Abdur-Rahmaan Janhangeer wrote:
> do you have something like
> 
> choice(balls)
> 
> >>> red  

Don't specify the "k=" (which defaults to 1 if you omit it) and use
the first element of the results:

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


> and subsequent repetitions for long enough yield approximately 2/5
> times r 2/5 times g and 1/5 b

You can sample it yourself:

>>> from collections import defaultdict
>>> a = defaultdict(int)
>>> for i in range(10000):
...     a[choices(data, weights=weights)[0]] += 1
... 
>>> dict(a)
{'green': 3979, 'red': 4008, 'blue': 2013}

though if you plan to, then it might be better/faster to use
cum_weights instead, calculating it once and then reusing it rather
than having choices() re-calculate the cumulative-weights on every
call.


> like one without random choice over list/tuples

Not sure what you mean by this.

-tkc





More information about the Python-list mailing list