-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay07-2.py
More file actions
71 lines (62 loc) · 2.06 KB
/
Day07-2.py
File metadata and controls
71 lines (62 loc) · 2.06 KB
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
71
import collections
# class Hand is a structure containing the card combination, the point value and the type of each hand
class Hand:
def __init__(self, line):
self.cards = list(line.split()[0])
self.points = int(line.split()[1])
self.label = self.getLabel()
# assigns the appropriate type for each hand
def getLabel(self):
cardCounter = collections.Counter(c for c in self.cards if c != 'J')
jokers = self.cards.count('J')
if not cardCounter or max(cardCounter.values()) + jokers == 5:
return "5oK"
elif max(cardCounter.values()) + jokers == 4:
return "4oK"
elif max(cardCounter.values()) + jokers == 3:
if min(cardCounter.values()) == 2:
return "FH"
else:
return "3oK"
elif list(cardCounter.values()).count(2) == 2:
return "2P"
elif max(cardCounter.values()) + jokers == 2:
return "1P"
else:
return "HC"
# compares a hand to another hand
def isSmaller(self, hand) -> bool:
for i, ch in enumerate(hand.cards):
if cardStrength.index(self.cards[i]) > cardStrength.index(ch):
return True
elif cardStrength.index(self.cards[i]) < cardStrength.index(ch):
return False
return False
# returns the position in the list where a hand belongs
# assumes that the list should be sorted from lowest to highest
def whereDoesItFit(hand: Hand, lst: list) -> int:
for i, item in enumerate(lst):
if hand.isSmaller(item):
return i
return len(lst)
hands = {}
labels = ["HC", "1P", "2P", "3oK", "FH", "4oK", "5oK"]
cardStrength = ["A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J"]
with open("input.txt") as f:
for line in f.readlines():
hand = Hand(line)
if hand.label not in hands:
hands[hand.label] = [hand]
else:
idx = whereDoesItFit(hand, hands[hand.label])
hands[hand.label].insert(idx, hand)
result2 = []
pt = 1
# iterates over the sorted hands in the dictionary (variable "hands") from lowest to highest value
# and calculates the number of points for each one
for l in labels:
if l in hands:
for item in hands[l]:
result2.append(item.points * pt)
pt += 1
print("Result 2:", sum(result2))