Python Puzzles
You have two dice; one is fair and the other unfair. The unfair dice rolls a 6 50% of the time.
What is the probability of choosing the unfair dice if you randomly choose a dice and roll a 6?
You can use Bayes theorem to provide a mathematical proof.
- The probability of the dice being unfair is 75%.
- The probability of the dice being fair is 25%.
import random
# initialize variables to count the number of times each dice is selected
unfair_dice = 0
fair_dice = 0
# initialize an empty list to hold the results
list = []
# simulate 10,000 rolls of a dice
for _ in range(10_000):
# randomly choose a dice, either 1 or 2
dice = random.randrange(1,3);
# dice 1 is unfair
if dice == 1:
# Probability of rolling a 6 is 50%
diceroll = random.randrange(5,7)
if diceroll == 6: list.append(dice)
# dice 2 is fair
if dice == 2:
diceroll = random.randrange(1,7)
if diceroll == 6: list.append(dice)
# determine the proportion of rolls for each dice
for x in list:
if x == 1:
unfair_dice = unfair_dice + 1
else:
fair_dice = fair_dice + 1
# print the probabilities of each dice being selected
print('The probability of the dice being fair is ' + '{0:.1%}'.format(fair_dice/len(list)))
print('The probability of the dice being unfair is ' + '{0:.1%}'.format(unfair_dice/len(list)))
