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.

  • 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.

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.


Sample elements from the lottery without replacement.

Parameters:sample_size (int) – The number of items to sample from the lottery.