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.

  • items (Iterable[~T]) – Items to choose from.
  • weight_key (Callable[[~T], int]) – A function that takes an item in items and returns a non-negative integer weight for that item.

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()
>>> lottery.sample(2)
['apple', 'cantelope']

Pick a random element from the lottery.

Return type:~T

Sample elements from the lottery without replacement.

Parameters:sample_size (int) – The number of items to sample from the lottery.
Return type:Iterable[~T]