here2share

# weighted_random.py

Feb 26th, 2021 (edited)
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.44 KB | None | 0 0
  1. # weighted_random.py
  2.  
  3. # in this example, weighted['BB'] should be 20x-2x the random chance
  4. # *** {'C': ~100, 'AAA': ~100, 'BB': ~1800}
  5.  
  6. from random import choice
  7.  
  8. def weighted_random(z, tries=1):
  9.     weighted = dict((k,0) for k in set(z))
  10.     for _ in range(tries):
  11.         r = choice(z)
  12.         weighted[r] += 1
  13.     return weighted
  14. #
  15. my_list = ['AAA'] + ['BB'] * 20 + ['C']
  16.  
  17. for _ in range(5):
  18.     results = weighted_random(my_list, 2000)
  19.     print results
Add Comment
Please, Sign In to add comment