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

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

Using random module

>>> import random

>>> # 0.0 <= float < 1.0
>>> random.random()
0.41360177662769904

>>> # 10.0 <= float < 20.0
>>> random.uniform(10,20)
15.743669918803288

>>> # 10 <= int <= 20  (can be 20)
>>> random.randint(10,20)
10

>>> # 10 <= int < 20  (even only, coz step=2)
>>> random.randrange(10,20,2)
16

>>> # choose from a list
>>> random.choice([1, 2, 3, 5, 9])
2

>>> # make a list into random order
>>> cards = range(52)
>>> random.shuffle(cards)  # order is random now
>>> cards[:5]   # get 5 cards
[37, 14, 42, 44, 6]

Weighted random choice

From Kevin Parks's recipe
import random

def w_choice(lst):
	n = random.uniform(0, 1)
	for item, weight in lst:
		if n < weight:
			break
		n = n - weight
	return item

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

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