Weighted Random Choice
Join the DZone community and get the full member experience.Join For Free
From Kevin Parks's recipe
import random def w_choice(lst): n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return itemUsage, similar to random.choice but must specify probabilities.
>>> x = w_choice( [('one',0.25), ('two',0.25), ('three',0.5)] )