I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:
def weighted_choice(choices):
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
assert False, "Shouldn't get here"