Last active
September 26, 2019 13:05
-
-
Save angeloped/5078a13db51a57db2740deddac9658c8 to your computer and use it in GitHub Desktop.
Random choice based on probability distribution.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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