Project Euler 54 - Poker Hands

Official link: https://projecteuler.net/problem=54

Thought Process

I did this a long time when I started learning python, but I really enjoyed coding this problem. I made a function which takes in a poker hand and return its "score" if you will, using this score I compare it to the other players hand

I have 4 mini functions and 1 main function

  1. value(x)

    • Returns a value of a card, T = 10, J = 11 etc

  2. suite_value(x)

    • Clubs = 1, Diamonds = 2, Spades = 3, Hearts = 4

  3. player_1_hand(hand)

    • Takes a string from the txt file, for example: "8C TS KC 9H 4S 7D 2S 5D 3S AC"

    • Returns ["8TK94", "CSCHS"] the hand along with corresponding suite of each card

  4. player_2_hand(hand)

    • Same as previous function except returns hand 2

    • ["7253A", "DSDSC"]

The main function is shown below

5. hand_rank(hands)

  • This function takes a list such as ["7253A", "DSDSC"] and returns it's score based on the table above, for example a hand with 4 7's, a 4 of a kind, would return [8, 7] where 8 is the big score and 7 is the lower score incase we we encounter a tie

  • I used the length of the set("7253A") for example

    1. If the length if 5, This implies we can have a High Card, Straight, Flush, Straight Flush or Royal Flush

    2. If the length is 4, this implies we have One Pair

    3. If the length is 3, we have Two Pairs or a Three of a Kind

    4. If the length is 2, we have a Four of a Kind or a Full House

  • Then I just coded simple formulas under each if statement using the str.count() function to return me a score

Interactive Code

Enter a poker hand input from the txt file such as: 8C TS KC 9H 4S 7D 2S 5D 3S AC

Code will output which player wins