SZanlongo
7/28/2016 - 2:37 PM

Weighted Choice

Weighted Choice

def weighted_choice(choices):
    """
    Given a set of choices, make a biased random selection based on each choice's weight
    :param choices: [tuple, tuple, ...]
        Choices is a list of tuples, where each tuple consists of the (item, weight)
    :return:  item
        Item that was chosen according to the random weight distribution
    """
    total = sum(w for c, w in choices)
    r = random.uniform(0, total)
    upto = 0
    for c, w in choices:
        if upto + w >= r:
            return c
        upto += w
    return None