Skip to content

Instantly share code, notes, and snippets.

@jakedobkin
Created December 15, 2011 20:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakedobkin/1482724 to your computer and use it in GitHub Desktop.
Save jakedobkin/1482724 to your computer and use it in GitHub Desktop.
Euler 54- Poker Hand Grader
# arrays for grading hands
numbers = ["2","3","4","5","6","7","8","9","T","J","Q","K","A"]
plays = ["0P","1P","2P","3K","4$","5F","6F","7F","8F","9F"]
# some functions we'll use- the basic approach for the grade function
# is to give each hand a string grade- when sorted, the better hand should come out on top
def l2n(letter):
index = numbers.index(letter)+2
return index
def grade(hand):
hcards = [""]*5
for j in range(0,5):
hcards[j]=hand[j*3:(j*3)+2]
card_nums = []
for l in range (0,5):
letter = hcards[l][0:1]
card_nums.append(l2n(letter))
card_nums.sort()
hplays=""
# next check for a straight
if card_nums[0]==card_nums[1]-1==card_nums[2]-2==card_nums[3]-3==card_nums[4]-4:
hplays=plays[4]
# then check for a flush
if hcards[0][1:2] == hcards[1][1:2] == hcards[2][1:2] ==hcards[3][1:2] == hcards[4][1:2]:
hplays = hplays+plays[5]
# correct for straight flush
if hplays==plays[4]+plays[5]:
hplays=plays[8]
# correct for royal flush
if hplays==plays[8] and card_nums[4]==14:
hplays=plays[9]
# now let's do the matching number cards, starting with 4 of a kind
histo = [0]*15
for x in range(2,15):
histo[x]=card_nums.count(x)
if 4 in histo:
hplays=plays[7]+str(histo.index(4)).zfill(2)
if 3 in histo and 2 in histo:
hplays=plays[6]+str(histo.index(3)).zfill(2)
if 3 in histo and 2 not in histo:
hplays=plays[3]+str(histo.index(3)).zfill(2)
if 2 in histo and 3 not in histo:
# here you have to see if there are 1 pair of 2s or 2pairs
paircount = histo.count(2)
if paircount == 2:
pairs = []*2
for y in range (2,15):
if histo[y]==2:
pairs.append(y)
hplays=plays[2]+str(max(pairs)).zfill(2)
else:
hplays=plays[1]+str(histo.index(2)).zfill(2)
if 1 in histo and 4 not in histo and 3 not in histo and 2 not in histo:
hplays=hplays+plays[0]
# now add high card to string
hplays=hplays+str(card_nums[4]).zfill(2)
return hplays
# import file, then run through it deciding matches
file = open('poker.txt','r').readlines()
count=0
for i in range(0,1000):
# read hand 1
hand1 = file[i][0:14]
hand2 = file[i][15:29]
print i
print hand1,"\n",hand2
print grade(hand1),grade(hand2)
grades = []
grades.append(grade(hand1))
grades.append(grade(hand2))
grades.sort()
if grades[1]==grade(hand1):
print "hand 1 wins \n"
count += 1
else:
print "hand 2 wins \n"
print count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment