project-euler/054_poker_hands.py

93 lines
2.5 KiB
Python

#!/usr/bin/env python3
def final():
r=block_to_list("data/054_poker.txt")
count=0
for i in r:
if compet(i[0],i[1]):
count+=1
return count
def compet(x,y):
a=pok_hand(x)
b=pok_hand(y)
av=[n for n in a]
bv=[n for n in b]
av.sort()
bv.sort()
i=1
while i<=len(av) and i<=len(bv):
if av[-i]!=bv[-i]:
if av[-i]>bv[-i]:
return True
else:
return False
for n in range(len(a[av[-i]])):
if a[av[-i]][n]!=b[bv[-i]][n]:
if a[av[-i]][n]>b[bv[-i]][n]:
return True
else:
return False
i+=1
def block_to_list(fn):
result=[]
with open(fn) as f:
for line in f:
s=line.split(" ")
result.append([s[:5],s[5:9]+[s[9][:2]]])
return result
def pok_hand(x):
v={'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}
suit=[n[1] for n in x]
val=[v[n[0]] for n in x]
high_com={1:sorted(val,reverse=True)}
if len(set(suit))==1:
#flush
high_com[6]=[0]
if len(set(val))<5:
d={i:0 for i in set(val)}
for i in val:
d[i]+=1
for k,v in d.items():
if v>1:
if v==2:
#pair
if not(2 in high_com):
high_com[2]=[k]
else:
high_com[2].append(k)
elif v==3:
#tris
high_com[4]=[k]
elif v==4:
#four of kind
high_com[8]=[k]
if (2 in high_com) and len(high_com[2])==2:
#two pairs
high_com[3]=sorted(high_com[2],reverse=True)
del high_com[2]
elif (2 in high_com) and (4 in high_com):
#full house
high_com[7]=[high_com[4],high_com[2][0]]
del high_com[4]
del high_com[2]
elif sorted(val)==list(range(sorted(val)[0],sorted(val)[0]+5)):
if 6 in high_com:
del high_com[6]
if sorted(val)[0]==10:
#royal_flush
high_com[10]=[0]
else:
#staright flsuh
high_com[9]=[sorted(val)[-1]]
else:
#straight
high_com[5]=[sorted(val)[-1]]
return high_com
if __name__ == '__main__':
print(final())