Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import Counter
- def get_puzzle_input(a_file_name: str) -> list[str]:
- with open(a_file_name) as INFILE:
- return [line.rstrip().split()[0] for line in INFILE if not line.startswith('#')]
- def sort_cards(a_card: str) -> int:
- rank_map = {
- 'K' : 2, 'Q' : 3, 'T' : 4,
- '9' : 5, '8' : 6, '7' : 7, '6' : 8,
- '5' : 9, '4' : 10, '3' : 11, '2' : 12,
- 'J' : 13, 'A' : 14 }
- return rank_map[a_card]
- def upgrade_hand(a_hand: str) -> str:
- hand_counter = Counter(a_hand)
- hand_set = set(hand_counter.keys())
- hand_set.discard('J')
- ranked_hand_set = sorted(hand_set, key=sort_cards)
- if hand_counter['J'] == 5:
- return 'KKKKK'
- if hand_counter['J'] == 4:
- for k in hand_counter:
- if k == 'J':
- pass
- else:
- return a_hand.replace('J', k)
- if hand_counter['J'] == 3:
- if len(ranked_hand_set) == 1:
- return ranked_hand_set[0] * 5
- else:
- return a_hand.replace('J', ranked_hand_set[0])
- if hand_counter['J'] == 2:
- if len(ranked_hand_set) == 1:
- return ranked_hand_set[0] * 5
- elif len(ranked_hand_set) == 2:
- for k, v in hand_counter.items():
- if k == 'J':
- pass
- elif v == 2:
- return a_hand.replace('J', k)
- else:
- return a_hand.replace('J', ranked_hand_set[0])
- if hand_counter['J'] == 1:
- if len(ranked_hand_set) == 4:
- return a_hand.replace('J', ranked_hand_set[0])
- elif len(ranked_hand_set) == 1:
- return ranked_hand_set[0] * 5
- elif len(ranked_hand_set) in [2, 3]:
- pairs = []
- three_of_a_kind = []
- for k, v in hand_counter.items():
- if v == 3:
- three_of_a_kind.append(k)
- elif v == 2:
- pairs.append(k)
- if len(three_of_a_kind) > 0:
- return a_hand.replace('J', three_of_a_kind[0])
- elif len(pairs) > 0:
- return a_hand.replace('J', sorted(pairs, key=sort_cards)[0])
- else:
- assert False, 'Why am I here?'
- else:
- assert False, 'Why am I here?'
- # No J card, return original hand
- return a_hand
- hands = get_puzzle_input('AOC2023\AOC2023D07.txt')
- print(f'{hands=}')
- for hand in hands:
- hand_upgraded = upgrade_hand(hand)
- print(f'{hand=}, {hand_upgraded=}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement