Saturday, January 8, 2011

Reference point (Part 2)

Project Euler Problem 54
import csv
import re

def facerank(face):
    return '23456789TJQKA'.find(face)

def handrank(hand):
    faces = ''.join(
        sorted([face for (face, suit) in hand], key=facerank)
    )
    is_straight = facerank(faces) != -1
    is_flush = len(set(suit for (face, suit) in hand)) == 1
    
    sorted_groups = sorted(
        [ (len(m.group(0)), facerank(m.group(1)))
            for m in re.finditer(r'(.)\1*', faces) ],
        reverse=True
    )
    
    return (
        [5] if is_flush and is_straight else
        [3, 1.2] if is_flush else
        [3, 1.1] if is_straight else
        [size for (size, member) in sorted_groups]
    ), sorted_groups

print sum(
    handrank(line[:5]) > handrank(line[5:])
        for line in csv.reader(open('poker.txt'), delimiter=" ")
)

Wow, just learned that you can "unzip" in this manner:
faces, suits = zip(*hand)
You can also use findall instead:
[ (len(xs), facerank(x))
    for xs, x in re.findall(r'((.)\2*)', faces) ]

No comments:

Post a Comment