wr (Weighted Random)

wr is a weighted random implementation in Python.

wr.choice can be fed both mappings (such as dictionaries) and sequences of pairs containing what to return and a integer representing their respective weight. It returns a the key of in case of mappings based on the weights defined in the key’s corresponding value.

The key can be anything hashable but the weight must be a integer.

Optionally you may feed wr.choice with a sequence of pairs.

Functions

wr.choice(data)

The main implementation of weighted random choice. (based on inplace algorithm)

Args:
data (Mapping or sequence of pairs): (returnable, weight)
Returns:
For Mappings: A key For sequences of pairs: [0] of a pair.

Usecase:

>>> print wr.choice({"hello": 80, "world": 20})
hello

Example

>>> import wr

>>> data = {'cat': 60, 'dog': 30, 'bird': 10}
>>> animal = wr.choice(data)
>>> print animal
cat # well, the cat had a good 60% shot at it.

Structures

{something_to_return: weight, something_else_to_return: weight}
# Or as a sequence:
[(something_to_return, weight), (something_else_to_return, weight)]

Installation

Install wr with pip install wr or just download wr.py and place it in your project directory.

Project Versions

Table Of Contents

This Page