Home > Project Euler, python > Project euler #54

Project euler #54

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          2C 3S 8S 8D TD          Player 2     
                Pair of Fives           Pair of Eights
	 	
2	 	5D 8C 9S JS AC          2C 5C 7D 8S QH          Player 1
                Highest card Ace        Highest card Queen
	 	
3	 	2D 9C AS AH AC          3D 6D 7D TD QD          Player 2
                Three Aces              Flush with Diamonds
	 	
4	 	4D 6S 9H QH QC          3D 6D 7H QD QS          Player 1     
                Pair of Queens          Pair of Queens
                Highest card Nine       Highest card Seven
	 	
5	 	2H 2D 4C 4D 4S          3C 3D 3S 9S 9D          Player 1
                Full House              Full House
                With Three Fours        with Three Threes
	 	
The file, poker.txt, contains one-thousand 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?

python:

import time

ts = time.time()

def highest_card(cards):
    vals = []
    for card in [card[0] for card in cards]:
        vals.append(int(specials[card]))
    return max(vals)

def has_pairs(cards, limit=1):
    cards = ''.join([card[0] for card in cards])
    pairs = 0
    for card in cards:
        if cards.count(card) == 2:
            cards = cards.replace(card, '')
            pairs += 1
    return pairs == limit

def has_tris(cards):
    cards = ''.join([card[0] for card in cards])
    for card in cards:
        if cards.count(card) == 3:
            return True

def has_straight(cards):
    cards = sorted([specials[card[0]] for card in cards])
    for i in range(len(cards)):
        try:
            diff = cards[i+1] - cards[i]
            if diff == 1:
                straight = True
            else:
                straight = False
                break
        except IndexError:
            pass
    return straight

def has_flush(cards):
    suits = ''.join([card[1] for card in cards])
    flush = False
    for suit in 'HCSD':
        if suits.count(suit) == 5:
            flush = True
    return flush

def has_full(cards):
    cards = ''.join([card[0] for card in cards])
    n = cards.count(cards[0])
    if n == 2 or n == 3:
        cards = cards.replace(cards[0], '')
        m = cards.count(cards[0])
        if n + m == 5: return True
    return False

def has_poker(cards):
    cards = ''.join([card[0] for card in cards])
    return (cards.count(cards[0]) == 4 or cards.count(cards[1]) == 4)

def check_card(cards):
    if has_straight(cards) and has_flush(cards) and \
       highest_card([card[0] for card in cards]) == 14:
        return 9
    elif has_straight(cards) and has_flush(cards):
        return 8
    elif has_poker(cards):
        return 7
    elif has_full(cards):
        return 6
    elif has_flush(cards):
        return 5
    elif has_straight(cards):
        return 4 
    elif has_tris(cards):
        return 3
    elif has_pairs(cards, 2):
        return 2
    elif has_pairs(cards):
        return 1
    else: return 0

def check_tie_pair(cards):
    cards = ''.join([card[0] for card in cards])
    for card in cards:
        if cards.count(card) == 2:
            return specials[card]

specials = {'1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7,
            '8':8, '9':9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}

file_in = open(r'poker.txt')
hands = file_in.readlines()
file_in.close()

count_p1 = 0
count_p2 = 0

for hand in hands:
    p1 = sorted(hand.split(' ')[:5])
    p2 = sorted(hand.rstrip().split(' ')[5:])
    score_p1 = check_card(p1)
    score_p2 = check_card(p2)
    if score_p1 > score_p2: count_p1 += 1
    elif score_p1 < score_p2: count_p2 += 1
    else:
        if score_p1 == 0:
            if highest_card(p1) > highest_card(p2):
                count_p1 += 1
            elif highest_card(p1) < highest_card(p2):
                count_p2 += 1
            
        elif score_p1 == 1: # tie pair
            if check_tie_pair (p1) > check_tie_pair(p2):
                count_p1 += 1
            elif check_tie_pair (p1) == check_tie_pair(p2):
                if highest_card(p1) > highest_card(p2):
                    count_p1 += 1
                elif highest_card(p1) < highest_card(p2):
                    count_p2 += 1
            else: count_p2 += 1
        if count_p1 + count_p2 == len(hands): break

print "problem euler 54: %s \nelapsed time: %ssec" %(
    count_p1, time.time() - ts)
Categorie:Project Euler, python
  1. Non c'è ancora nessun commento.
  1. No trackbacks yet.

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...

%d blogger cliccano Mi Piace per questo: