Solution
- Define Probabilities: The first step is to define the probabilities of drawing each color of the ball. According to the problem statement, 40% of the balls are black, 35% are white, and the rest (100% - 40% - 35% = 25%) are blue.
-
Generate a Random Number: We then generate a random number between 0 and 1. This random number represents the probability of selecting a ball of any color.
-
Determine the Color:
We use the generated random number to determine the color of the ball that is drawn from the container. We compare this random number with the cumulative probabilities of each color. If the random number falls within the range of a certain color's probability, we select that color.
For example, if the random number is less than 0.40 (the probability of black), we select a black ball. If the random number is greater than or equal to 0.40 but less than 0.40 + 0.35 (the probability of black + white), we select a white ball. Otherwise, we select a blue ball.
Return the Color: Finally, we return the color of the drawn ball.
import random
def draw_ball():
# Define the probabilities
probabilities = {'black': 0.40, 'white': 0.35, 'blue': 0.25}
# Generate a random number between 0 and 1
rand_num = random.random()
# Determine the color of the drawn ball based on the probabilities
if rand_num < probabilities['black']:
return 'black'
elif rand_num < probabilities['black'] + probabilities['white']:
return 'white'
else:
return 'blue'
# Example usage
drawn_ball = draw_ball()
print("The drawn ball is", drawn_ball)