Weighted choice in python

If you need to choose a values from some set with a different probabilities
Works in Python 3.6+

random.choices([1,2], weights=[0.001, 0.8], k=1)[0]

To proove lets run function 100k times:

arr = [ch[0] for ch in [random.choices([1,2], weights=[0.001, 0.8], k=1) for _ in range(100000)]]
>>> arr.count(1), arr.count(2)
(114, 99886)
#python #statistics
menu 7
Ivan Borshchov profile picture
Nov 01, 2017
by Ivan Borshchov

Best related

Other by Ivan Borshchov