Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Using random module

   1  
   2  >>> import random
   3  
   4  >>> # 0.0 <= float < 1.0
   5  >>> random.random()
   6  0.41360177662769904
   7  
   8  >>> # 10.0 <= float < 20.0
   9  >>> random.uniform(10,20)
  10  15.743669918803288
  11  
  12  >>> # 10 <= int <= 20  (can be 20)
  13  >>> random.randint(10,20)
  14  10
  15  
  16  >>> # 10 <= int < 20  (even only, coz step=2)
  17  >>> random.randrange(10,20,2)
  18  16
  19  
  20  >>> # choose from a list
  21  >>> random.choice([1, 2, 3, 5, 9])
  22  2
  23  
  24  >>> # make a list into random order
  25  >>> cards = range(52)
  26  >>> random.shuffle(cards)  # order is random now
  27  >>> cards[:5]   # get 5 cards
  28  [37, 14, 42, 44, 6]

Weighted random choice

From Kevin Parks's recipe
   1  
   2  import random
   3  
   4  def w_choice(lst):
   5  	n = random.uniform(0, 1)
   6  	for item, weight in lst:
   7  		if n < weight:
   8  			break
   9  		n = n - weight
  10  	return item

Usage, similar to random.choice but must specify probabilities.
   1  
   2  >>> x = w_choice( [('one',0.25), ('two',0.25), ('three',0.5)] )

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS