Last active
August 29, 2015 14:08
-
-
Save hahastudio/b6bb65b6eccb11d154fb to your computer and use it in GitHub Desktop.
Probabilistic choice for python
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 prob_choice(items): | |
total_prob = sum(i[1] for i in items) | |
r = random.uniform(0, total_prob) | |
for value, prob in items: | |
if r < prob: | |
return value | |
r -= prob | |
return items[-1][0] | |
# eg | |
items = [('a', 0.5), ('b', 0.3), ('c', 0.2)] | |
#>>> prob_choice(items) | |
#'c' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@hahastudio
请问下, 这个实现的目的是什么呢? 和 random.choice() 有什么区别吗? 谢谢.