04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 10 ■ BATTERIES INCLUDED 229<br />

random number in the range from 1 to 10 (inclusive), you would use randrange(1,11) (or, alternatively,<br />

randrange(10)+1), and if you want a random odd positive integer lower than 20, you<br />

would use randrange(1,20,2).<br />

The function random.choice chooses (uniformly) a random element from a given sequence.<br />

The function random.shuffle shuffles the elements of a (mutable) sequence randomly,<br />

such that every possible ordering is equally likely.<br />

The function random.sample chooses (uniformly) a given number of elements from a given<br />

sequence, making sure that they’re all different.<br />

■Note For the statistically inclined, there are other functions similar to uniform that return random numbers<br />

sampled according to various other distributions, such as betavariate, exponential, Gaussian, and several others.<br />

Examples<br />

Generating a random date in a given range. In the following examples, I use several of the functions from the<br />

time module described previously. First, let’s get the real numbers representing the limits of the time interval (the<br />

year 2005). You do that by expressing the date as a time tuple (using -1 for day of the week, day of the year, and<br />

daylight savings, making Python calculate that for itself) and calling mktime on these tuples:<br />

from random import *<br />

from time import *<br />

date1 = (2005, 1, 1, 0, 0, 0, -1, -1, -1)<br />

time1 = mktime(date1)<br />

date2 = (2006, 1, 1, 0, 0, 0, -1, -1, -1)<br />

time2 = mktime(date2)<br />

Then you generate a random number uniformly in this range (the upper limit excluded):<br />

>>> random_time = uniform(time1, time2)<br />

Then, you simply convert this number back to a legible date:<br />

>>> print asctime(localtime(random_time))<br />

Mon Jun 24 21:35:19 2005<br />

Creating an electronic die-throwing machine. For this example, let’s ask the user how many dice to throw, and<br />

how many sides each one should have. The die-throwing mechanism is implemented with randrange and a for<br />

loop:<br />

from random import randrange<br />

num = input('How many dice? ')<br />

sides = input('How many sides per die? ')<br />

sum = 0<br />

for i in range(num): sum += randrange(sides) + 1<br />

print 'The result is', sum

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!