Last active
January 8, 2019 11:07
-
-
Save pervognsen/51d999a8aded0acf44bb2a1c47b95a93 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class DiscreteDistribution: | |
| def __init__(self): | |
| self.total_weight = 0 | |
| self.points = {} | |
| def add(self, point, weight): | |
| assert point not in self.points | |
| self.points[point] = weight | |
| self.total_weight += weight | |
| def remove(self, point): | |
| self.total_weight -= self.points[point] | |
| del self.points[point] | |
| def sample(self, num_samples): | |
| items = iter(self.points.items()) | |
| point, cum_weight = next(items) | |
| x = 0.0 | |
| dx = self.total_weight / num_samples | |
| for i in range(num_samples): | |
| yield point | |
| x += dx | |
| while x >= cum_weight: | |
| point, weight = next(items) | |
| cum_weight += weight | |
| dist = DiscreteDistribution() | |
| dist.add('a', 10) | |
| dist.add('b', 5) | |
| dist.add('c', 3) | |
| print(list(dist.sample(6))) # ['a', 'a', 'a', 'a', 'b', 'c'] | |
| dist.remove('a') | |
| print(list(dist.sample(6))) # ['b', 'b', 'b', 'b', 'c', 'c'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment