Weighted random choice in python

It's easy to use numpy.

import numpy as np

d = [("foo", 98), ("bar", 844), ("baz", 1028)]
a, w = zip(*d)
print(a, w)
# -> ('foo', 'bar', 'baz') (98, 844, 1028)

w2 = np.array(w) / sum(w)
v = np.random.choice(a, p=w2)
print(v)
# -> baz


#Verification
from collections import Counter
c = [ np.random.choice(a, p=w2) for i in range(sum(w)) ]
print(Counter(c))
# -> Counter({'baz': 1051, 'bar': 824, 'foo': 95})

It's almost right.

numpy unused version

It's okay to put numpy just for this ... In that case, you may want to use bisect.

import bisect
import itertools
import random

d = [("foo", 98), ("bar", 844), ("baz", 1028)]
a, w = zip(*d)
print(a, w)

ac = list(itertools.accumulate(w))
f = lambda : bisect.bisect(ac, random.random() * ac[-1])
v = a[f()]
print(v)

#Verification
from collections import Counter
c = [ a[f()] for i in range(sum(w)) ]
print(Counter(c))
# -> Counter({'baz': 1010, 'bar': 851, 'foo': 109})

It's almost right.

Recommended Posts

Weighted random choice in python
Random walk in Python
Balanced Random Forest in python
Use Random Forest in Python
Testing with random numbers in Python
Create a random string in Python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Weighted Random Extraction: Walker's Alias Method (Python)
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram in python
Csv in python
Disassemble in Python
Reflection in Python
Disease classification in Random Forest using Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
[Python] Disease classification in random forest-with LDA-
LiNGAM in Python
Flatten in python
flatten in python
Testing methods that return random values in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python