This module provides for the generation of pseudorandom numbers.
Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin. For, as has been pointed out several times, there is no such thing as a random number—there are only methods to produce random numbers, and a strict arithmetic procedure of course is not such a method. | ||
| -- John von Neumann | ||
choice(S)
Returns a randomly selected element from an iterable .
S
>>> for i in range(9): print choice ( ['s', 'h', 'd', 'c'] ), ... s c c h c s s h d
normalvariate(m,s)
Generate a normally distributed pseudorandom number with
mean and
standard deviation m.
s
randint(x,y)
Returns a random integer in the closed interval
[,x];
that is, any result r will satisfy y.
x <= r <= y
>>> for i in range(20): print randint(1,6), ... 3 4 6 3 2 1 1 2 1 2 1 2 3 3 3 5 6 4 4 2
random()
Returns a random float in the half-open
interval [0.0, 1.0); that is, for any result
,
r0.0 <= .
r < 1.0
>>> for count in range(48):
... print "{0:.3f}".format(random()),
... if (count % 12) == 11: print
...
0.012 0.750 0.899 0.339 0.371 0.561 0.358 0.931 0.822 0.990 0.682 0.847
0.245 0.541 0.992 0.151 0.394 0.335 0.702 0.885 0.986 0.350 0.417 0.748
0.918 0.103 0.109 0.328 0.423 0.180 0.203 0.689 0.600 0.794 0.201 0.008
0.564 0.920 0.906 0.469 0.510 0.818 0.142 0.589 0.590 0.290 0.650 0.889
randrange([start,]stop[,step])
Return a random element from the sequence range( start,stop,step).
>>> from random import * >>> for i in range(35): print randrange(4), ... 0 2 2 2 1 1 2 3 1 3 3 2 2 2 3 0 2 0 0 1 2 0 2 1 1 1 2 2 2 1 1 3 1 1 2 >>> for i in range(35): print randrange(1,5), ... 3 3 2 1 1 1 4 4 3 2 1 1 3 2 1 2 4 4 1 4 2 4 4 1 1 1 1 1 4 4 1 1 2 2 1 >>> range(2,18,5) [2, 7, 12, 17] >>> for i in range(28): print randrange(2,18,5), ... 12 2 7 2 17 17 7 7 12 17 17 2 7 17 12 7 7 12 17 17 7 12 7 7 7 7 7 7
shuffle(L)
Randomly permute the elements of a sequence .
L
Here's an example. First we build a (small) deck of cards, using a list comprehension to build a list of all possible combinations of three ranks (ace, king, queen) and four suits (spades, hearts, diamonds, and clubs). Then we shuffle the deck twice and inspect the results.
>>> ranks = 'AKQ' >>> suits = 'shdc' >>> deck = [ r+s ... for s in suits ... for r in ranks ] >>> deck ['As', 'Ks', 'Qs', 'Ah', 'Kh', 'Qh', 'Ad', 'Kd', 'Qd', 'Ac', 'Kc', 'Qc'] >>> shuffle(deck) >>> deck ['Qh', 'Ks', 'Kh', 'As', 'Kc', 'Kd', 'Qd', 'Qc', 'Ah', 'Ad', 'Qs', 'Ac'] >>> shuffle(deck) >>> deck ['As', 'Qs', 'Ks', 'Kc', 'Ad', 'Kh', 'Qh', 'Ac', 'Ah', 'Qc', 'Qd', 'Kd']
uniform(x,y)
Returns a random float in the half-open interval [,x); that is, each
result y
will satisfy r.
x <=
r < y
An assortment of other pseudorandom distributions is available. See the Python Library Reference for details.