Skip to content

Instantly share code, notes, and snippets.

@hahastudio
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hahastudio/b6bb65b6eccb11d154fb to your computer and use it in GitHub Desktop.
Save hahastudio/b6bb65b6eccb11d154fb to your computer and use it in GitHub Desktop.
Probabilistic choice for python
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'
@kzinglzy
Copy link

@hahastudio
请问下, 这个实现的目的是什么呢? 和 random.choice() 有什么区别吗? 谢谢.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment