baseplate.random
¶
Extensions to the standard library random module.
-
class
baseplate.random.
WeightedLottery
(items, weight_key)¶ 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: - items – A sequence of items to choose from.
- weight_key – A function that takes an
item in
items
and returns a non-negative integer weight for that item.
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']
-
pick
()¶ Pick a random element from the lottery.