#Cards and Beans #Simulations of the experiments described in Lecture 2. from pylab import * #Cards. We model the deck as the list of integers #0 to 51, so the rank of card i is 1 + i//4 and the suit #is i%4 #Pull two cards from the deck and estimate the probability #that they have the same rank. There are options for the #number of trials and whether this is done with or without #replacement. Default is with replacement. def card_sim(numtrials, repl=True): count=0 for j in range(numtrials): sample=choice(arange(52),2,replace=repl) if sample[0]//4==sample[1]//4: count+=1 return count/numtrials #A bin contains b beans of each of three colors (0,1,2). #Pull out 3 beans (with or without replacement). What is #the probability that all three are different? def bean_sim(b,numtrials,repl=True): beans=[0]*b+[1]*b+[2]*b #the jar count=0 for j in range(numtrials): sample=choice(beans,3,replace=repl) if (0 in sample) and (1 in sample) and (2 in sample): count+=1 return count/numtrials #Return a random permutation of the integers 1,...,n def random_perm(n): return choice(arange(1,n+1),n,replace=False)