Reputation: 23
first time using this platform so hope I'm doing it the right way. I'm currently in high school and we have this project with this description: Calculate the probability that when you deal 5 cards (without repeating cards) of poker you have two pairs. I have already done the programming with some notes I took from class for the five cards:
import random
def generatedeck():
deck = []
for i in range(1,14):
deck.extend([i]*4)
return deck
def main():
seed = int(input())
random.seed(seed)
for e in range(1000):
deck = generatedeck()
hand = []
for i in range(5):
pos = random.randint(0,len(deck)-1)
card = deck.pop(pos)
hand.append(card)
print(hand)
if __name__=='__main__':
main()
The thing is, I really don't know how to proceed to calculate the probability.
We do have some notes/examples for this homework.
For example if your hand is: 1,1,2,3,3 (there's a pair of 1 and a pair of 3) [The event is fulfilled] 3,Q,3,3,3 (poker) [not fulfilled]
The simulation needs to run 1000 times
Simulation examples: (Input: 0, Output: 0.055) (Input: 11, Output: 0.047) (Input: 42, Output: 0.046)
Let me know what you think of the code in general, and if you think there is a better way to have the cards dealt. Thank you in advance for all your help!
Upvotes: 1
Views: 258
Reputation: 217
I would just like to preface that this answer is to get the experimental probability of a two pair occurring.
How I have fixed it is that after the five card hand is dealt, I loop through the hand and use list.count to return how many of those cards are in a deck. I check if that number is equal to two. This means that there is one pair. Then inside the if statement that find the first pair, I loop through the array again and find if there is a pair that is not equal to the first pair. If this is true, meaning that there is a two pair in that hand, I add to a variable that keeps track of how many two pairs there has been in 1000 iterations. After iterating through 1000 times I divide the number of two pairs by 1000 and then the experimental probability is reached. The code looks as follows:
import random
def generatedeck():
deck = []
for i in range(1,14):
deck.extend([i]*4)
return deck
def main():
seed = int(input("Enter a seed for Random: "))
random.seed(seed)
NumTwoPairs = 0
num = 0
for e in range(1000):
deck = generatedeck()
hand = []
for i in range(5):
pos = random.randint(0,len(deck)-1)
card = deck.pop(pos)
hand.append(card)
for elem in hand: #checking for the two pair
if hand.count(elem) == 2:
for el in hand:
if hand.count(el) == 2 and el != elem:
NumTwoPairs += 1
#print(hand)
break
break
return NumTwoPairs
#print(hand)
print(main()/1000)
For the seed of 1
the returned output is
0.049
Upvotes: 1