Question

This activity needs to be completed in the Python language. This program will simulate part of...

This activity needs to be completed in the Python language.

This program will simulate part of the game of Poker.

This is a common gambling game comparing five-card hands against each other with the value of a hand related to its probability of occurring. This program will simply be evaluating and comparing hands, and will not worry about the details of dealing and betting.

Here follow the interesting combinations of cards, organized from most common to least common:

  • Pair -- two cards are of the same rank (such as sevens or kings); the other three are all different rank
  • Two Pair -- consists of two different pairs (such as sevens and kings) plus a fifth card of different rank
  • Three of a kind -- three cards are of the same rank ; the other two are of different rank
    the score is the sum of all five dice
  • Straight -- five cards of consecutive rank (such as Queen, Jack, Ten, Nine, Eight)
  • Flush -- five cards all of the same suit (such as Spades)
  • Full House -- three of one rank, two of another;
  • Four of a Kind -- four of the five cards are of the same rank
  • Straight Flush -- five cards all of the same suit and of consecutive rank

The provided test code produces two hands and compares them. In each case below, two hands are displayed in a two-character shorthand, with a short description of the hand. The third line in each case describes the better hand with longer words (if the short-hand is not yet recognizable).

Of special note is that in a straight, an Ace may either be higher than a King or lower than a Two (but never both at the same time)

KH TH 8C 4D 3D -- Nothing King high
TS 9S 8D 6H 4H -- Nothing Ten high
King of Hearts  Ten of Hearts  Eight of Clubs  Four of Diamonds  Three of Diamonds  
QC TD 6C 4S 3S -- Nothing Queen high
AC QS 7C 7S 2D -- Pair Seven
Ace of Clubs  Queen of Spades  Seven of Clubs  Seven of Spades  Two of Diamonds  
AS QH JD 9D 6S -- Nothing Ace high
AD AH JH TC 7D -- Pair Ace
Ace of Diamonds  Ace of Hearts  Jack of Hearts  Ten of Clubs  Seven of Diamonds  
8S 7H 6D 5C 3C -- Nothing Eight high
QD 9H 5D 5H 2H -- Pair Five
Queen of Diamonds  Nine of Hearts  Five of Diamonds  Five of Hearts  Two of Hearts  
AC 5H 4H 3H 2H -- Straight Five high
6S 5S 4S 3S 2S -- Straight Flush Six high
Six of Spades  Five of Spades  Four of Spades  Three of Spades  Two of Spades  
AD KD JD TD 4D -- Flush Ace high
AS QS 9S 7S 3S -- Flush Ace high
Ace of Diamonds  King of Diamonds  Jack of Diamonds  Ten of Diamonds  Four of Diamonds

The Assigned Functions

longest_suit:
Application Concept: Identify the suit with the most cards, and return the cards in that suit.

Given a list of tuples, identify the longest subset that can be found with the same encoded suit (the second value in each tuple). For example, longest_suit([(1,3),(2.1),(3,2),(3,3)]) returns [(1,3),(3,3)]Hint: first divide all the cards into the four separate lists, and then decide which list is longest.

If two suits happen to have the same number of cards, it does not matter which is returned. This function is only of interest for identifying flushes and straight flushes, where five are of the same suit.  

count_ranks:
Application Concept: Identify the number of two's, three's, four's, etc. in a hand, and return all the counts.

Given a list of tuples, look at the consider the first value of each tuple, and then figure out how to get a cumulative count for all of those values. Since there are 13 possible ranks of cards, the returned list will have 13 values (many of which may be zero).

For example, identifying a Full House simply requires knowing that there are three cards of one rank and two of another, which is much easier to determine with a count on the ranks than comparing cards to each other. Two Aces and Three Kings (coded as [(0,0),(0,2),(1,0),(1,2),(1,3)] would return [2,3,0,0,0,0,0,0,0,0,0,0,0]

contains_straight:
Application Concept: Determine whether a hand contains cards of consecutive ranks.

Hint: the count_ranks results can be very helpful here, since it already identifies what cards are present in the hand, without considering the suits. The list slice feature lets you focus on a particular part of the list -- such as elements [0:5] consider just the first five elements.

Consider this thought problem. If I handed you five cards that might have any number from 4 to 8 on them, how would you know there was a straight? Could you come up with a test that would work equally well if I handed you ten cards in the same range?

The general straight can be down very quickly without a loop, because there is one simple function call that can be used to identify the highest card (from those count_ranks), and then another test using the inmembership test to see if that highest card is the top of a straight.

And there would also be another simple way to get the special case of the Ace-low straight.

The return value from this function is to be either True along with the numeric code for the highest card (when there is a straight), or simply False

evaluate_hand:
Categorizes a hand as consisting of a Full House, Straight, etc.

The return value consists of two parts -- the hand type (Full House, Straight, etc.) and something indicating the rank of the most relevant cards (the highest of a Straight or Flush, or what card is doubled in a Pair).

Two special circumstances will require returning two different card ranks: Full House and Two Pair.

The provided test function calls this one for every hand it generates, so the return values must be as expected.

better_hand:
Determines which of two poker hands is the better hand. There may be multiple parts to the decision:

  • if they have different types, whichever type is better (Full House beats a Straight)
  • if they have equal types involving sets of repeated ranks, compare the sets (4 Aces beats 4 Kings)
  • Single cards are compared down the line (Ace, King, Ten beats Ace, King, Five)

If all cards of both hands are of equal rank, the two hands are equal. Suits will not be relevant except for identifying flushes.

The same link as above (Links to an external site.) provides more details and examples of comparing hands. Feel free to ignore any discussion about unbeatable hands.

Good use of existing functions will not require any loops in this function. Of special interest would be the meaning of comparing two results from count_ranks with each other.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in Python and comments for better understanding:

Here I am attaching these 3 files:

  • poker_test.py
  • poker_hand_work.py
  • poker_hand_import.py

Code for poker_test.py:

def count_ranks(hand):
        '''Returns the number of twos, threes, etc. in a hand'''
        counts = [0]*13        # initialize counts for all 13 ranks     
        for card in hand:
                counts[card[0]]+=1
        return counts

def longest_suit(hand):
        '''Returns the longest subset of a hand in the same suit
    Five cards in one suit counts as a Flush'''
        suit_sets = [[],[],[],[]]                # four empty lists
        maxLength = 0
        longestList = []
        for card in hand:
                suit_sets[card[1]].append(card)
        for suit in suit_sets:
                if len(suit) > maxLength:
                        maxLength = len(suit)
                        longestList     = suit
        return longestList

def contains_straight(counts):
        i = 0
        while i <= 9:
                straightList = counts[i:i+5]
                if all(x == 1 for x in straightList):
                        return (True, i);
                i+=1
        if all(y == 1 for y in counts[10:14]) and counts[0] == 1:
                return (True, 10);
        return (False,0)

def findPairsIndex(counts):
        indexPostList = []
        indexPos = 0
        while len(indexPostList)<2:
                indexPos = counts.index(2,indexPos)
                indexPostList.append(indexPos)
                indexPos += 1
        return indexPostList


def evaluate_hand(hand):
        kind = ""
        rank = 0
        counts = count_ranks(hand)
        highestInCounts = counts.index(next(filter(lambda x: x!=0, counts)))
        isStraight,highest = contains_straight(counts)
        longestSuit = longest_suit(hand)
        if isStraight and len(longestSuit) == 5:
                kind = 'Straight Flush'
                rank = highest
        elif 4 in counts:
                kind = 'Four of a Kind'
                rank = counts.index(4)
        elif 3 in counts and 2 in counts:
                kind = 'Full House'
                rank = (counts.index(3), counts.index(2))
        elif len(longestSuit) == 5:
                kind = 'Flush'
                rank = highestInCounts
        elif isStraight:
                kind = 'Straight'
                rank = highest
        elif 3 in counts:
                kind = 'Three of a Kind'
                rank = counts.index(3)
        elif counts.count(2) == 2:
                kind = 'Two pair'
                rank = findPairsIndex(counts)
        elif 2 in counts:
                kind = 'Pair'
                rank = counts.index(2)
        else:
                kind = 'Nothing'
                rank = highestInCounts
        return (kind,rank)


if __name__ == '__main__':
        hand=[(0,0),(0,0),(3,0),(1,0),(1,0)]
        # print(count_ranks(hand))
        # hand = [(1,3),(2,1),(3,2),(3,3)]
        # print(longest_suit(hand))
        counts=[1,0,0,0,0,0,0,0,1,1,1,1,1]
        # isStraight,i = contains_straight(counts)
        # print(isStraight)
        # print(i)
        kind,rank = evaluate_hand(hand)
        print(kind,rank)

Code Screenshots:

Code for poker_hand_work.py:

if __name__ == '__main__':
    from poker_hand_import import shuffle_deck,summarize,test, \
        card_name,short_name,print_hand,print_short_hand

# A couple lists describing the cards of a hand
# The ranks are listed so the highest card will be easy to identify

suits = ['Clubs','Diamonds','Hearts','Spades']

ranks = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight',
         'Seven', 'Six', 'Five', 'Four', 'Three', 'Two']

types = ['Straight Flush','Four of a Kind','Full House','Flush',
         'Straight','Three of a Kind','Two Pair','Pair','Nothing']


# The Student Work for this assignment is Below This Line

# Here are some functions to help categorize a hand

def count_ranks(hand):
        '''Returns the number of twos, threes, etc. in a hand'''
        counts = [0]*13        # initialize counts for all 13 ranks     
        for card in hand:
                counts[card[0]]+=1
        return counts

def longest_suit(hand):
        '''Returns the longest subset of a hand in the same suit
    Five cards in one suit counts as a Flush'''
        suit_sets = [[],[],[],[]]                # four empty lists
        maxLength = 0
        longestList = []
        for card in hand:
                suit_sets[card[1]].append(card)
        for suit in suit_sets:
                if len(suit) > maxLength:
                        maxLength = len(suit)
                        longestList     = suit
        return longestList

def contains_straight(counts):
        i = 0
        while i <= 9:
                straightList = counts[i:i+5]
                if all(x == 1 for x in straightList):
                        return (True, i);
                i+=1
        if all(y == 1 for y in counts[10:14]) and counts[0] == 1:
                return (True, 10);
        return (False,0)


def evaluate_hand(hand):
        kind = ""
        rank = 0
        counts = count_ranks(hand)
        highestInCounts = counts.index(next(filter(lambda x: x!=0, counts)))
        isStraight,highest = contains_straight(counts)
        longestSuit = longest_suit(hand)
        if isStraight and len(longestSuit) == 5:
                kind = 'Straight Flush'
                rank = highest
        elif 4 in counts:
                kind = 'Four of a Kind'
                rank = counts.index(4)
        elif 3 in counts and 2 in counts:
                kind = 'Full House'
                rank = (counts.index(3), counts.index(2))
        elif len(longestSuit) == 5:
                kind = 'Flush'
                rank = highestInCounts
        elif isStraight:
                kind = 'Straight'
                rank = highest
        elif 3 in counts:
                kind = 'Three of a Kind'
                rank = counts.index(3)
        elif counts.count(2) == 2:
                kind = 'Two pair'
                rank = findPairsIndex(counts)
        elif 2 in counts:
                kind = 'Pair'
                rank = counts.index(2)
        else:
                kind = 'Nothing'
                rank = highestInCounts
        return (kind,rank)


def better_hand(hand1,hand2):
    '''Determines which of two hands is better than the other
    Returns None if they are of equal value'''
    kind1,rank1 = evaluate_hand(hand1)
    kind2,rank2 = evaluate_hand(hand2)


if __name__ == '__main__':
    for i in range(1):
        test()

Code Screenshots:

Code for poker_hand_import.py:

# Poker Hand Evaluator
# Given a set of cards representing a poker hand,
# identifies the nature of that hand.

import random
from poker_hand_work import evaluate_hand,better_hand

# A couple lists describing the cards of a hand
# The ranks are listed so the highest card will be easy to identify

suits = ['Clubs','Diamonds','Hearts','Spades']

ranks = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight',
         'Seven', 'Six', 'Five', 'Four', 'Three', 'Two']

types = ['Straight Flush','Four of a Kind','Full House','Flush',
         'Straight','Three of a Kind','Two Pair','Pair','Nothing']

# Some descriptive items

def card_name(card):
    '''Returns the name of a card, given its coded rank and suit'''
    return ranks[card[0]] + ' of ' + suits[card[1]]

def print_hand(hand):
    '''Prints the long names of the cards in a hand'''
    for card in sorted(hand):
        print(card_name(card),end='  ')
    print()

def short_name(card):
    '''Identifies a card by a very brief name'''
    return 'AKQJT98765432'[card[0]] + 'CDHS'[card[1]]

def print_short_hand(hand):
    '''Prints the short names of the cards in a hand'''
    for card in sorted(hand):
        print(short_name(card),end=' ')

def summarize(hand):
    if hand is None:
        print('No winning hand')
        return
    hand_type,rank = evaluate_hand(sorted(hand))
    print_short_hand(hand)
    print('--',hand_type,end=' ')
    if hand_type == 'Full House':
        print(f'{ranks[rank[0]]}s over {ranks[rank[1]]}s')
    elif hand_type == 'Two Pair':
        print(f'{ranks[rank[0]]}s and {ranks[rank[1]]}s')
    elif hand_type in ['Four of a Kind','Three of a Kind','Pair']:
        print(ranks[rank])
    else:
        print(f'{ranks[rank]} high')

# Randomly generate hands of rare types

def random_flush():
    '''Creates a flush, that may or may not be a straight'''
    suit = random.randint(0,3)
    hand = []
    for rank in random.sample(range(13),5):
        hand.append( (rank,suit) )
    return sorted(hand)

def random_straight():
    '''Creates a straight, that may or may not be a flush'''
    suit = random.randint(0,3)
    other = random.randint(0,3)
    first = random.randint(-1,8)
    if first == -1:     # Create Ace-low straight
        first = 8
        hand = [ (0,other) ]
    else:
        hand = [ (first,other) ]
    for i in range(1,5):
        hand.append( (first+i,suit) )
    return sorted(hand)

def shuffle_deck():
    '''Returns a complete deck of cards, shuffled; each card is a tuple'''
    deck = []
    for suit in range(4):
        for rank in range(13):
            deck.append( (rank, suit) )
    random.shuffle(deck)
    return deck

# Here a few tests to start with:
def test():
    deck = shuffle_deck()
    for j in range(0,40,10):
        summarize(deck[j:j+5])
        summarize(deck[j+5:j+10])
        print_hand(better_hand(sorted(deck[j:j+5]),sorted(deck[j+5:j+10])))
        
    hand1 = random_straight()
    hand2 = random_straight()
    summarize(hand1)
    summarize(hand2)
    print_hand(better_hand(hand1,hand2))
    
    hand1 = random_flush()
    hand2 = random_flush()
    summarize(hand1)
    summarize(hand2)
    print_hand(better_hand(hand1,hand2))

Hope it helps.Thank you.

Add a comment
Know the answer?
Add Answer to:
This activity needs to be completed in the Python language. This program will simulate part of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • discrete structure Recall that a standard deck of 52 cards has 4 suits (hearts, diamonds, spades, and clubs), each of w...

    discrete structure Recall that a standard deck of 52 cards has 4 suits (hearts, diamonds, spades, and clubs), each of which has 13 ranks: 2-10, Jack, Queen, King, and Ace (in order from lowest to highest). Order of cards in a hand does not matter (a) (10 points) A full house is 3 cards of one rank and 2 of another rank. How many full houses are there in a 5-card hand if either the pair or the 3 of...

  • This has to be done in Haskell only. Write a program that: Given 2 poker hands...

    This has to be done in Haskell only. Write a program that: Given 2 poker hands (5 cards) in list of tuples form (ex. hand1 = [(1,0),(2,0),(3,0),(4,0),(5,0)]). Each tuple represents a card where first number of a tuple is its value (1=Ace, 2=2,...,10=10, 11=Jack, 12=Queen, 13=King) and second number its suit (0=Clubs, 1=Diamonds, 2=Hearts, 3=Spades) so (1,0) will be Ace of Clubs, or (5,2) will be 5 of Hearts, etc. Rule website: https://www.fgbradleys.com/et_poker.asp These hands are generated by an end...

  • Need help writing this program! Thanks in advance. Project4 Specifications: Determine Poker Hand A poker hand...

    Need help writing this program! Thanks in advance. Project4 Specifications: Determine Poker Hand A poker hand can be stored in a two-dimensional array. The statement: Dim aryintCards(4,14) as Integer (See AryCardExample.xlsx excel spreadsheet) declares an array which the first subscript 1-4 are the four suits and the second subscript ranges over the card denominations: 1-14: Ace, 2, ..., 10, Jack, Queen, King, Ace (repeated). First subscript of 0 is Total of each denomination. Second subscript of 0 is Total of...

  • C++ Your solution should for this assignment should consist of five (5) files: Card.h (class specification...

    C++ Your solution should for this assignment should consist of five (5) files: Card.h (class specification file) Card.cpp (class implementation file) DeckOfCards.h (class specification file) DeckOfCards.cpp (class implementation file) 200_assign6.cpp (application program) NU eelLS Seven UT Diamonds Nine of Hearts Six of Diamonds For your sixth programming assignment you will be writing a program to shuffle and deal a deck of cards. The program should consist of class Card, class DeckOfCards and an application program. Class Card should provide: a....

  • A standard deck of cards consists of four suits (clubs, diamonds, hearts, and spades), with each...

    A standard deck of cards consists of four suits (clubs, diamonds, hearts, and spades), with each suit containing 13 cards (ace, two through ten, jack, queen, and king) for a total of 52 cards in all. How many 7-card hands will consist of exactly 3 kings and 2 queens?

  • Python Programming: An individual playing card is represented as a string of two characters: • the...

    Python Programming: An individual playing card is represented as a string of two characters: • the first character is from "23456789TJQKA" and represents the rank, i.e., the number or value of the card. (Note that 10 is encoded as letter T to make all card ranks to be single letters) • the second character is from "cdhs" and represents the suit (clubs, diamonds, hearts and spades respectively). For example, "Jd" would be the jack of diamonds, and "4s" would be...

  • Write in Java! Do NOT write two different programs for Deck and Card, it should be...

    Write in Java! Do NOT write two different programs for Deck and Card, it should be only one program not 2 separate ones!!!!!! !!!!!!!!!!!!!!!Use at least one array defined in your code and two array lists defined by the operation of your code!!!!!!!!!!!!!!!!!!!!! The array should be 52 elements and contain a representation of a standard deck of cards, in new deck order. (This is the order of a deck of cards new from the box.) The 2 Array lists...

  • A standard poker deck of 52 cards has four suits, (symbols C, H, S, and D) and thirteen ranks (sy...

    A standard poker deck of 52 cards has four suits, (symbols C, H, S, and D) and thirteen ranks (symbols A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, and K). Every card in the deck has both a value and a suit.1 A poker hand is any set of 5 cards from the standard poker deck. There are some special hands in poker, and these have ranks (i.e. some are better, some are worse). From best...

  • Assume you are dealt the following hand in poker: K of hearts, Q of hearts, 10 of spades, 3 hearts, 7 clubs. For this se...

    Assume you are dealt the following hand in poker: K of hearts, Q of hearts, 10 of spades, 3 hearts, 7 clubs. For this set of problems, we are keeping both the K and Q of hearts. So, If you keep the King and Queen of hearts find: P (getting a pair of Kings and/or Queens)…be sure to exclude the probability of getting either three or four Kings or Queens. Also consider the probability of one or two pairs. P(3...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT