Skip to content

Instantly share code, notes, and snippets.

@angeloped
Last active September 26, 2019 13:05
Show Gist options
  • Save angeloped/5078a13db51a57db2740deddac9658c8 to your computer and use it in GitHub Desktop.
Save angeloped/5078a13db51a57db2740deddac9658c8 to your computer and use it in GitHub Desktop.
Random choice based on probability distribution.
import random
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:
break
upto += w
if c == None:
weighted_choice(choices)
else:
return c
print(weighted_choice([('Mcdonalds',100.0),('Max\'s Restaurant',40.0),('Jollibee',3.0)]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment