"""
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)