Skip to content

Instantly share code, notes, and snippets.

@robperc
Last active February 28, 2016 04:25
Show Gist options
  • Save robperc/456317e26f7672d0ee32 to your computer and use it in GitHub Desktop.
Save robperc/456317e26f7672d0ee32 to your computer and use it in GitHub Desktop.
Assortment of functions for selecting weighted random elements from a dictionary of 'element: weight' pairs.
"""
Assortment of functions for selecting weighted random elements from a dictionary of 'element: weight' pairs.
"""
import random
def getRand(items):
"""
Selects random element from items and returns.
Args:
items (list): list of items to select random element from.
Returns:
Random element from list.
"""
return items[random.randint(0, len(items))]
def getWeightedRand(weights):
"""
Selects random key from weights dictionary based on value associated with key.
Args:
weights (dict): dictionary of 'element: frequency' pairs.
Returns:
Random element from weighted dictionary depending on weight.
"""
items = sum([[key] * val for key, val in weights.iteritems()], [])
return getRand(items)
def getReducedWeightedRand(weights):
"""
Selects random key from weights dictionary based on value associated with key.
Reduces weights to whole number percentage of sum of weights before selecting.
This is less precise but handles weights with large frequency numbers much better.
Args:
weights (dict): dictionary of 'element: weight' pairs.
Returns:
Random element from weighted dictionary depending on weight.
"""
total = float(sum(weights.values()))
for key, val in weights.iteritems():
weights[key] = int(val / total * 100.0)
return getWeightedRand(weights)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment