12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

126 Chapter 13. Casestudy: datastructure selection13.2 RandomnumbersGiven the same inputs, most computer programs generate the same outputs every time, so they aresaidtobedeterministic. Determinismisusuallyagoodthing,sinceweexpectthesamecalculationto yield the same result. For some applications, though, we want the computer to be unpredictable.Games arean obvious example, but there aremore.Making a program truly nondeterministic turns out to be not so easy, but there are ways to makeit at least seem nondeterministic. One of them is to use algorithms that generate pseudorandomnumbers. Pseudorandomnumbersarenottrulyrandombecausetheyaregeneratedbyadeterministiccomputation, but just by looking at the numbers it is all but impossible to distinguish them fromrandom.The random module provides functions that generate pseudorandom numbers (which I will simplycall “random” fromhere on).The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Eachtimeyou callrandom,you get thenext number inalong series. To see asample, run thisloop:import randomfor i in range(10):x = random.random()print xThefunctionrandinttakesparameterslowandhighandreturnsanintegerbetweenlowandhigh(including both).>>> random.randint(5, 10)5>>> random.randint(5, 10)9To choose anelement fromasequence at random, you can usechoice:>>> t = [1, 2, 3]>>> random.choice(t)2>>> random.choice(t)3Therandommodulealsoprovidesfunctionstogeneraterandomvaluesfromcontinuousdistributionsincluding Gaussian, exponential, gamma, and afew more.Exercise 13.5 Write a function named choose_from_hist that takes a histogram as defined inSection 11.1 and returns a random value from the histogram, chosen with probability in proportiontofrequency. For example, forthis histogram:>>> t = ['a', 'a', 'b']>>> h = histogram(t)>>> print h{'a': 2, 'b': 1}your function should’a’withprobability 2/3 and'b'withprobability 1/3.

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

Saved successfully!

Ooh no, something went wrong!