baseplate.lib.random
¶
Extensions to the standard library random module.
-
class
baseplate.lib.random.
WeightedLottery
(items, weight_key)[source]¶ A lottery where items can have different chances of selection.
Items will be picked with chance proportional to their weight relative to the sum of all weights, so the higher the weight, the higher the chance of being picked.
- Parameters
- Raises
ValueError
if any weights are negative or there are no items.
An example of usage:
>>> words = ["apple", "banana", "cantelope"] >>> lottery = WeightedLottery(words, weight_key=len) >>> lottery.pick() 'banana' >>> lottery.sample(2) ['apple', 'cantelope']