2023-12-07 21:38:22 +00:00
|
|
|
from collections import Counter
|
|
|
|
|
|
|
|
def calculate_rank(hand):
|
|
|
|
card_ranks = {'2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7, '9': 8, 'T': 9, 'J': 10, 'Q': 11, 'K': 12, 'A': 13}
|
|
|
|
# substitute cards with their ranks
|
2023-12-08 09:21:36 +00:00
|
|
|
hand = [card_ranks[c] for c in hand]
|
2023-12-07 21:38:22 +00:00
|
|
|
cnt = Counter(hand)
|
2023-12-08 09:21:36 +00:00
|
|
|
rank = 0
|
|
|
|
match sorted(cnt.values()):
|
|
|
|
case [5]: rank = 7
|
|
|
|
case [1, 4]: rank = 6
|
|
|
|
case [2, 3]: rank = 5
|
|
|
|
case [1, 1, 3]: rank = 4
|
|
|
|
case [1, 2, 2]: rank = 3
|
|
|
|
case [1, 1, 1, 2]: rank = 2
|
|
|
|
case [1, 1, 1, 1, 1]: rank = 1
|
|
|
|
|
2023-12-07 21:38:22 +00:00
|
|
|
return (rank, hand)
|
|
|
|
|
|
|
|
|
|
|
|
def part1(inp):
|
|
|
|
total = 0
|
|
|
|
hands = [l.strip().split() for l in inp.strip().split("\n")]
|
|
|
|
hands = sorted(hands, key=lambda hb: calculate_rank(hb[0]))
|
|
|
|
for rank, hand in enumerate(hands):
|
|
|
|
hand, bid = hand
|
|
|
|
total += (rank + 1) * int(bid)
|
|
|
|
return total
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
sample_input = """
|
|
|
|
32T3K 765
|
|
|
|
T55J5 684
|
|
|
|
KK677 28
|
|
|
|
KTJJT 220
|
|
|
|
QQQJA 483
|
|
|
|
"""
|
2023-12-08 09:21:36 +00:00
|
|
|
res = part1(sample_input)
|
|
|
|
print(f"part 1 example: {res}")
|
|
|
|
assert res == 6440
|
2023-12-07 21:38:22 +00:00
|
|
|
|
|
|
|
import sys
|
|
|
|
if len(sys.argv) == 2:
|
|
|
|
with open(sys.argv[1]) as f:
|
|
|
|
res = part1(f.read())
|
|
|
|
print(f"Part 1, res={res}")
|