Issue
I am attempting to answer the following question:
For this exercise, you are to complete the function two_pair_prob, which estimates the probability of rolling two pairs with n independent dice rolls, over n trials. A "pair" is two dice with the same value, and "two pairs" is two distinct pairs of dice with the same value. For example, the following sequences contain two pairs over 5 rolls: (2, 1, 1, 3, 2), (3, 4, 3, 6, 4). Note that we are not interested in the probability of rolling exactly two pairs, but rather the probability of rolling two pairs or more. For example, the following also count as two pairs over 5 rolls: (1, 1, 1, 2, 2), (1, 1, 1, 1, 2), (1, 1, 1, 1, 1). The following do not count as two pairs over 5 rolls: (1, 1, 2, 3, 1), (3, 4, 6, 5, 3), (2, 3, 4, 5, 6).
The solution I have built is as follows:
def roll_dice():
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
if dice1==dice2:
return True
def two_pair_prob(n_rolls, n_trials):
twopairs = 0
for x in range(1,n_trials+1):
y = n_rolls
count = 0
while y > 0:
if roll_dice():
count+=1
else:
pass
y-=1
if count > 1:
twopairs+=1
return twopairs/n_trials
However, when I run a test for the code, it never finishes running and doesn't provide a result. I feel I may be misinterpreting the question and what a "two-pair" is.
Solution
Below code works fine for me:
import random
def roll_dice(n):
return [random.randint(1, 6) for _ in range(n)]
def has_two_pairs_or_more(rolls):
counts = {}
for roll in rolls:
counts[roll] = counts.get(roll, 0) + 1
count_greater_than_1 = sum(count > 1 for count in counts.values())
count_greater_than_3 = any(count > 3 for count in counts.values())
return count_greater_than_1 >= 2 or count_greater_than_3
def two_pair_prob(n, m):
two_pair_count = 0
for _ in range(m):
rolls = roll_dice(n)
if has_two_pairs_or_more(rolls):
two_pair_count += 1
probability = two_pair_count / m
return probability
n_rolls = 5
n_trials = 100000
result = two_pair_prob(n_rolls, n_trials)
print(f"The estimated probability of rolling two pairs or more over {n_rolls} rolls and {n_trials} trials is: {result}")
Answered By - TheHungryCub
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.