-
Notifications
You must be signed in to change notification settings - Fork 0
/
07-2.py
70 lines (47 loc) · 1.56 KB
/
07-2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from collections import Counter, defaultdict
from enum import IntEnum, auto
from operator import itemgetter
with open("input.txt") as f:
lines = f.read().splitlines()
class HandType(IntEnum):
FIVE_OF_A_KIND = auto()
FOUR_OF_A_KIND = auto()
FULL_HOUSE = auto()
THREE_OF_A_KIND = auto()
TWO_PAIRS = auto()
ONE_PAIR = auto()
HIGH_CARD = auto()
CARDS = ["A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J"]
def calculate_strength(hand):
cards = Counter(hand)
if "J" in cards:
j = cards.pop("J")
if not cards:
return HandType.FIVE_OF_A_KIND
cards[max(cards, key=cards.get)] += j
if len(cards) == 1:
return HandType.FIVE_OF_A_KIND
if len(cards) == 2:
if 4 in cards.values():
return HandType.FOUR_OF_A_KIND
return HandType.FULL_HOUSE
if len(cards) == 3:
if 3 in cards.values():
return HandType.THREE_OF_A_KIND
return HandType.TWO_PAIRS
if len(cards) == 4:
return HandType.ONE_PAIR
return HandType.HIGH_CARD
def compare_cards(cards):
return [CARDS.index(card) for card in cards[0]]
strengths = defaultdict(list)
for line in lines:
hand, bid = line.split()
bid_number = int(bid)
strengths[calculate_strength(hand)].append((hand, bid_number))
bids = []
for key in sorted(strengths):
values = sorted(strengths[key], key=itemgetter(0))
for value in sorted(values, key=compare_cards):
bids.append(value[1])
print(sum(bid * i for i, bid in enumerate(reversed(bids), start=1)))