Last active
July 16, 2018 12:39
-
-
Save sumerc/74ebc1002d407109f1be82ecfd20b095 to your computer and use it in GitHub Desktop.
O(lgN) weighted random python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from bisect import bisect | |
class WeightedRandom2(object): | |
def __init__(self, weights): | |
# init interval tree | |
self._psum = [] | |
self._wsum = 0 | |
for k,v in weights.items(): | |
assert v > 0, "weight must be a positive integer" | |
self._wsum += v | |
self._psum.append(self._wsum) | |
def generate(self): | |
rnd = random.random() * self._wsum | |
return bisect(self._psum, rnd) | |
# Simple test | |
from collections import Counter | |
c = Counter() | |
wr = WeightedRandom2({1:90,2:5,3:5}) | |
for _ in range(20000): | |
c[wr.generate()] += 1 | |
print(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment