A Monte Carlo Simulation to Draw 3 same Color Balls Without Replaced From A Bucket With 3 Red Balls and 3 Green Balls

You have a bucket with 3 red balls and 3 green balls. Assume that once you draw a ball out of the bucket, you don't replace it. What is the probability of drawing 3 balls of the same color?

Write a Monte Carlo simulation to solve the above problem. Feel free to write a helper function if you wish.

 

def noReplacementSimulation(numTrials):
    '''
    Runs numTrials trials of a Monte Carlo simulation
    of drawing 3 balls out of a bucket containing
    3 red and 3 green balls. Balls are not replaced once
    drawn. Returns the a decimal - the fraction of times 3 
    balls of the same color were drawn.
    '''
    # Your code here
    sameColorNum = 0.0 
    for i in range(numTrials):
       redBallNum , buleBallNum = 0.0, 0.0
       balls = [0, 0, 0, 1, 1, 1]
       for k in range(3):
           draw = random.choice(balls)
           balls.remove(draw)
           if draw == 0:
               redBallNum += 1
           else:
               buleBallNum += 1

       if redBallNum == 3 or buleBallNum == 3:
           sameColorNum += 1
    return sameColorNum / numTrials
noReplacementSimulation(100000)

  0.10043

posted @ 2018-12-04 19:12  WWBlog  阅读(426)  评论(0编辑  收藏  举报