slight optimization

main
HeNine 12 months ago
parent 00d4f8cfd1
commit 247ad030a0

@ -4,26 +4,22 @@ ORDERING = "123456789TJQKA"
def do_task(infile): def do_task(infile):
hands = [(line.split()[0], int(line.split()[1])) for line in infile.split("\n")] hands = [(line.split()[0], int(line.split()[1])) for line in infile.split("\n")]
hands_parsed = [] hands.sort(key=evaluate_hand)
for hand, value in hands:
cards = dict(zip("123456789TJQKA", [0] * len(ORDERING)))
for card in hand:
cards[card] += 1
hands_parsed.append((hand, value, cards))
hands_parsed.sort(key=evaluate_hand)
score_sum = 0 score_sum = 0
for rank, (_, score, _) in enumerate(hands_parsed, start=1): for rank, (_, score) in enumerate(hands, start=1):
score_sum += rank * score score_sum += rank * score
return score_sum return score_sum
def evaluate_hand(h): def evaluate_hand(h):
(hand, _, cards) = h (hand, _) = h
cards = dict.fromkeys("123456789TJQKA", 0)
for card in hand:
cards[card] += 1
cv = max(cards.values()) << 4 cv = max(cards.values()) << 4

@ -4,30 +4,26 @@ ORDERING = "J123456789TQKA"
def do_task(infile): def do_task(infile):
hands = [(line.split()[0], int(line.split()[1])) for line in infile.split("\n")] hands = [(line.split()[0], int(line.split()[1])) for line in infile.split("\n")]
hands_parsed = [] hands.sort(key=evaluate_hand)
for hand, value in hands:
cards = dict(zip("123456789TQKA", [0] * len(ORDERING)))
j = 0
for card in hand:
if card != "J":
cards[card] += 1
else:
j += 1
hands_parsed.append((hand, value, cards, j))
hands_parsed.sort(key=evaluate_hand)
score_sum = 0 score_sum = 0
for rank, (_, score, _, _) in enumerate(hands_parsed, start=1): for rank, (_, score) in enumerate(hands, start=1):
score_sum += rank * score score_sum += rank * score
return score_sum return score_sum
def evaluate_hand(h): def evaluate_hand(h):
(hand, _, cards, j) = h (hand, _) = h
cards = dict.fromkeys("123456789TQKA", 0)
j = 0
for card in hand:
if card != "J":
cards[card] += 1
else:
j += 1
cv = max(cards.values()) << 4 cv = max(cards.values()) << 4

Loading…
Cancel
Save