day 7, saved by Counter

This commit is contained in:
2025-09-08 01:46:10 +02:00
parent 6fe70f851f
commit d165384617
3 changed files with 116 additions and 0 deletions

56
d07/part1.py Normal file
View File

@@ -0,0 +1,56 @@
import sys
from collections import Counter as C
from functools import cmp_to_key as ctk
def score(h:str) -> int: # get type of a hand
D = C(h)
E = C(v for k,v in D.items())
if 5 in E: # five of a kind
return 7
elif 4 in E: # four of a kind
return 6
elif 3 in E and 2 in E: # full house
return 5
elif 3 in E: # three of a kind
return 4
elif 2 in E and E[2] == 2: # two pairs
return 3
elif 2 in E:
return 2
else: # high card
return 1
H = list(reversed('AKQJT98765432'))
def compareH(h1, h2):
for a,b in zip(h1,h2):
if H.index(a) < H.index(b):
return 1
elif H.index(a) > H.index(b):
return -1
return 0
def compare(T1, T2): # return >:-1, ==:0, <:1
h1, s1, *_ = T1
h2, s2, *_ = T2
s1 = score(h1)
s2 = score(h2)
if s1 < s2:
return 1
elif s2 < s1:
return -1
else:
return compareH(h1,h2)
L = [ l.split() for l in sys.stdin.read().splitlines()]
L = [[h,int(b)] for [h,b] in L]
for h,b in L:
print(h, score(h))
pass
L.sort(key=ctk(compare))
print(
sum((i+1)*b for i,(h,b) in enumerate(reversed(L)))
)