0

I am trying to check if there is two pairs in a hand that is random. I have it right now where it'll print one pair so it prints the number of occurrences of that card so if there are 2 twos it'll be 2 x 2 so the first number is the occurrence then the second number is the card number and then to print one pair.

How do I make it where it'll print two pairs instead so checking in a hand of 5 if there is let's say for example 2 x 2 and 2 x 5 so a pair of 2 and 5 then to print out "two pairs".

I added in numbers = cards.count(card) and for the if statement below it then numbers == 2 So that if there is one pair and one pair it prints two pairs and the probability of getting it.

def twopair():
    count = 0
    while True:
        cards = []
        for i in range(5):
            cards.append(random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]))
        stop = False
        for card in cards:
            number = cards.count(card) # Returns how many of this card is in your hand
            numbers = cards.count(card)
            print(f"{number} x {card}")
            if(number == 2 and numbers == 2):
                print("One Pair")
                stop = True
                break
        if stop:
            break
        else:
            count += 1
    print(f'Count is {count}')
l.m
  • 131
  • 1
  • 10

1 Answers1

2

Have a look at the Counter from the collections module. https://docs.python.org/3/library/collections.html#collections.Counter

import random
from collections import Counter


def twopair():
    while True:
        cards = []
        for i in range(5):
            cards.append(random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]))

        counted_cards = Counter(cards)
        two_most_common, count = zip(*counted_cards.most_common(2))

        count_to_message = {
            (1, 1): "Nothing",
            (2, 1): "One Pair",
            (3, 1): "Three of a Kind",
            (4, 1): "Four of a Kind",
            (5, 1): "Whoops, who's cheating",
            (2, 2): "Two Pairs",
            (3, 2): "Full House",
        }

        msg = count_to_message[count]
        print(msg)
        if msg == "Two Pairs":
            break


twopair()
Sebastian Loehner
  • 1,302
  • 7
  • 5