You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

90 lines
3.0 KiB

#!/usr/bin/env python3
import sys
from functools import cmp_to_key
def classify_hand(hand):
shand = sorted(list(hand))
sets = set(shand)
if len(sets) == 1: return 'five'
elif shand.count(shand[0]) == 4 or shand.count(shand[1]) == 4: return 'four'
elif (shand[0] == shand[1] and shand[2] == shand[3] == shand[4]) or (shand[3] == shand[4] and shand[0] == shand[1] == shand[2]): return 'full'
elif shand.count(shand[0]) == 3 or shand.count(shand[1]) == 3 or shand.count(shand[2]) == 3: return 'three'
elif len(sets) == 3: return 'twop'
elif len(sets) == 4: return 'onep'
elif len(sets) == 5: return 'high'
def classify_hand2(hand):
joker = hand.count('J')
shand = sorted(list(hand))
sets = set(shand)
sets = sets.difference(set(['J']))
if joker > 3 or len(sets) == 1: return 'five'
elif joker == 3: return 'four'
elif joker == 2:
if len(sets) == 2: return 'four'
else: return 'three'
elif joker == 1:
if len(sets) == 2:
if shand.count(shand[0]) == 3 or shand.count(shand[1]) == 3 or shand.count(shand[2]) == 3:
return 'four'
else: return 'full'
elif len(sets) == 3: return 'three'
else: return 'onep'
def compare_hands(hand1, hand2):
hand_order = ['five', 'four', 'full', 'three', 'twop', 'onep', 'high']
ORDER = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2']
r1 = hand_order.index(classify_hand(hand1))
r2 = hand_order.index(classify_hand(hand2))
if r1 < r2: return 1
elif r2 < r1: return -1
else:
for i in range(5):
if ORDER.index(hand1[i]) < ORDER.index(hand2[i]): return 1
if ORDER.index(hand2[i]) < ORDER.index(hand1[i]): return -1
return 1
def compare_hands2(hand1, hand2):
hand_order = ['five', 'four', 'full', 'three', 'twop', 'onep', 'high']
ORDER = ['A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J']
if 'J' in hand1: r1 = hand_order.index(classify_hand2(hand1))
else: r1 = hand_order.index(classify_hand(hand1))
if 'J' in hand2: r2 = hand_order.index(classify_hand2(hand2))
else: r2 = hand_order.index(classify_hand(hand2))
if r1 < r2: return 1
elif r2 < r1: return -1
else:
for i in range(5):
if ORDER.index(hand1[i]) < ORDER.index(hand2[i]): return 1
if ORDER.index(hand2[i]) < ORDER.index(hand1[i]): return -1
return 1
if __name__ == '__main__':
lines = [line.strip('\n') for line in open(sys.argv[1])]
bids = {}
for line in lines:
hand, bid = line.split(' ')
bids[hand] = int(bid)
# challenge 1
res1 = 0
for i, hand in enumerate(sorted(bids.keys(),key=cmp_to_key(compare_hands))):
res1 += (i+1) * bids[hand]
res1 = str(res1)
print(f"challenge 1:\n{res1}\n")
# challenge 2
res2 = 0
for i, hand in enumerate(sorted(bids.keys(),key=cmp_to_key(compare_hands2))):
res2 += (i+1) * bids[hand]
res2 = str(res2)
print(f"challenge 2:\n{res2}\n")