Coupon Collector Problem and Python
Collecting Coupons: This is a famous problem in Mosteller's book.
Coupons in cereal boxes are numbered 1 to 5, and a set of one of each is required for a prize. With one coupon per box, how many boxes on the average are required to make a complete set?
Here is a python program to simulate it
"""We store the outputs in a list a until we get all the coupons
The coupons are generated from the randint function which generates
both the end values
The sum variable keep tracks of number of boxes we have been counting
"""
import random
flag = 1
a=[]
sum = 0
n = 1000 # number of times you want to run the experiment
coupNum = 30 # number of different coupons
for i in range(n):
count = 0
a=[]
flag =1
while flag:
x=random.randint(1,coupNum)
#generates random number between 1 and coupNum inclusive
count += 1
# print(x)
if x not in a:
a.append(x)
flag = 1
elif len(a)==coupNum:
flag=0
# print(count)
sum = sum+count
# print(a,count,sum)
del a[:] #delete the list
print(sum/n)
Coupons in cereal boxes are numbered 1 to 5, and a set of one of each is required for a prize. With one coupon per box, how many boxes on the average are required to make a complete set?
Here is a python program to simulate it
"""We store the outputs in a list a until we get all the coupons
The coupons are generated from the randint function which generates
both the end values
The sum variable keep tracks of number of boxes we have been counting
"""
import random
flag = 1
a=[]
sum = 0
n = 1000 # number of times you want to run the experiment
coupNum = 30 # number of different coupons
for i in range(n):
count = 0
a=[]
flag =1
while flag:
x=random.randint(1,coupNum)
#generates random number between 1 and coupNum inclusive
count += 1
# print(x)
if x not in a:
a.append(x)
flag = 1
elif len(a)==coupNum:
flag=0
# print(count)
sum = sum+count
# print(a,count,sum)
del a[:] #delete the list
print(sum/n)
Labels: Monte Carlo, Probability, Python
1 Comments:
thanks ! needed this for my maths class, I'm a teacher learning to code and would like to share ideas with my students about running simulations.
]Best wishes
Ken
Post a Comment
<< Home