def weighted_random ads total sum ad score for ad in ads randint total

1
2
3
4
5
6
7
def weighted_random(ads):
total = sum(ad["score"] for ad in ads)
r = randint(1, total)
for ad in ads:
r -= ad["score"]
if r <= 0:
return ad