Project Euler 54: Compare hands in a game of poker and determine a winner
Problem Description
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
 High Card: Highest value card.
 One Pair: Two cards of the same value.
 Two Pairs: Two different pairs.
 Three of a Kind: Three cards of the same value.
 Straight: All cards are consecutive values.
 Flush: All cards of the same suit.
 Full House: Three of a kind and a pair.
 Four of a Kind: Four cards of the same value.
 Straight Flush: All cards are consecutive values of same suit.
 Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
Consider the following five hands dealt to two players:
Hand  Player 1  Player 2  Winner  
1  5H 5C 6S 7S KD
Pair of Fives

2C 3S 8S 8D TD
Pair of Eights

Player 2  
2  5D 8C 9S JS AC
Highest card Ace

2C 5C 7D 8S QH
Highest card Queen

Player 1  
3  2D 9C AS AH AC
Three Aces

3D 6D 7D TD QD
Flush with Diamonds

Player 2  
4  4D 6S 9H QH QC
Pair of Queens
Highest card Nine 
3D 6D 7H QD QS
Pair of Queens
Highest card Seven 
Player 1  
5  2H 2D 4C 4D 4S
Full House
With Three Fours 
3C 3D 3S 9S 9D
Full House
with Three Threes 
Player 1 
The file, poker.txt, contains onethousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1’s cards and the last five are Player 2’s cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player’s hand is in no specific order, and in each hand there is a clear winner.
How many hands does Player 1 win?
Analysis
If we can quantify each hand into an array of tuples we can quickly compare each hand and determine a winner or a tie.
The first tuple would consist between 2 and 5 elements representing the frequency of card values sorted in descending order. The second tuple would consist of the same number of elements as the first but describe the value sorted and weighted by frequency in descending order.
Let’s check out how this would look for a few typical hands for both players:
p1 = TH 6H 9H QH JH [(1, 1, 1, 1, 1), (12, 11, 10, 9, 6)], score = 0
p2 = 9H 4D JC KS JS [(2, 1, 1, 1), (11, 13, 9, 4)], score = 1
p1 = 7C 7S KC KS JC [(2, 2, 1), (13, 7, 11)], score = 2
p2 = 7H 7D KH KD 9S [(2, 2, 1), (13, 7, 9)], score = 2
Ties in similar scores are broken by checking the second tuple
By simply comparing hands as p1>p2 we can determine the winner between the two players. The only complication left is to calculate and rank straights and flushes.
Project Euler 54 Solution
Runs < 0.100 seconds in Python 2.7.from collections import Counter
from urllib2 import urlopen
file_url = 'https://projecteuler.net/project/resources/p054_poker.txt'
hands = (line.split() for line in urlopen(file_url))
values = {r:i for i,r in enumerate('23456789TJQKA', start=2)}
straights = [(v, v1, v2, v3, v4) for v in range(14, 5, 1)] + [(14, 5, 4, 3, 2)]
ranks = [(1,1,1,1,1),(2,1,1,1),(2,2,1),(3,1,1),(),(),(3,2),(4,1)]
def hand_rank(hand):
score = zip(*sorted(((v, values[k]) for
k,v in Counter(x[0] for x in hand).items()), reverse=True))
score[0] = ranks.index(score[0])
if len(set(card[1] for card in hand)) == 1: score[0] = 5 # flush
if score[1] in straights: score[0] = 8 if score[0] == 5 else 4 # str./str. flush
return score
print "Project Euler 54 Solution =", sum(hand_rank(hand[:5]) > hand_rank(hand[5:]) for hand in hands)
Use this link to get the Project Euler 54 Solution Python 2.7 source.Answer
Slowly swipe from either end beginning with the white vertical bar to get an idea of the starting or ending digits. For less drama, just double click the answer area. The distance between the two bars will give you an idea of the magnitude. Touch devices can tap and hold the center of the box between the two bars and choose define to reveal the answer.Afterthoughts

No afterthoughts yet.
The best solution I have ever seen！！！！
love you
Instead of manually coding the rank combinations, you can do it so:
from itertools import combinations_with_replacement
ranks = [sorted(i, reverse=True) for j in range(1,6) for i in combinations_with_replacement(range(1,5), j) if sum(i)==5]
# %timeit: 54 us
PS. Your idea of scoring Poker is great!
Thank you so much for posting such an elegant solution. I’ve learned tons from this, honestly.
Just a heads up, I’m pretty sure this doesn’t account for A2345 straights. However, it’s still valid for the Euler problem, as pokers.txt contains no A2345 straights.
A quick fix I know, just an if statement to check. I was contemplating whether it was worth reviving the dead, but I figured you’d want to know.
To clarify as to why A2345 straights don’t work (and only against other straights), it’s because score[1] will be (14,5,4,3,2) rather than its true score of (5,4,3,2,1)
Good observation! I haven’t really thought about that; I’ll have to look at it when I find some time.
Glad it helped you out, and thanks for commenting. You should be proud of yourself for figuring it out. There’s a lot going on and it took me some time to get my head around it all again.
Great solution.
I think, for flush and straight, if you have sorted the values, you can just compare the first and the last.
Also, with sorted values for four of a kind you can compare 1 and 4 and also 2 and 5 and one has to be true.
You know I never thought of that. I will incorporate your ideas into this solution to make it easier to understand. Thanks for your observation.
For straight, comparing only first and last doesn’t work. See the following full house:
22266
First and last of this sorted array are [2] and [6] yet it isn’t a straight.
I have seen this problem in the past but I have never seen such a creative solution. Thanks for sharing this with others.
TJ