CIS 111 Random numbers

Objectives

  • Create pseudorandom numbers within a given range
  • Use pseudorandom numbers to solve problems

Overview

  • To use the random library: import random
  • Random numnber generators use seed values to start at a specific place in a sequence.
  • The random number generator will create the same sequence of random numbers for a given seed value.
  • To seed the random number generator based on the system time: random.seed(None)
  • You can also specify specific starting points in the sequence by providing a specific integer value.

Common functions used with random

FunctionPurpose
seed(None) seed the random number generator
getrandbits(n) returns a random int with n bits
randrange(start, stop) returns a random integer from start through stop-1
randrange(start, stop, step) returns a random integer from start through stop-1 which is a multiple of step from the start value
randint(low, high) returns a random integer between low and high (inclusive)
choice(seq) returns a random element from the supplied sequence
shuffle(seq) shuffles the specified sequence in place
sample(population, k) returns a list of k unique items from the specified population (a sequence or a set)
random() returns a random float in the range 0.0 to less than 1.0
uniform(low, high) returns a random float in the range low to high (inclusive)

Roll a die

import random print(random.randint(1, 6))

Roll two dice

import random print(random.randint(1, 6) + random.randint(1, 6))

Display ten random integers from 1 ... 100

for i in range(11): print(random.randint(1, 100))

Display a histogram for 1000 rolls of two dice

import random print() freq = [0] * 13 for roll in range(0, 1000): count = random.randint(1,6) + random.randint(1,6) freq[count] = freq[count] + 1 for ndx in range(2, 13): print("{0:2}: {1}".format(ndx, "*" * round(freq[ndx]/10)))

Deal a deck of cards

import random suit = [ "Spades", "Diamonds", "Clubs", "Hearts" ] rank = [ "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" ] deck = [] for st in suit: for rk in rank: deck.append(rk + " of " + st) random.shuffle(deck) print(deck)