Let's see how far I get this year.
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.

day07-1.py 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from collections import Counter
  2. from helpers import Helper
  3. helper = Helper(debug=True)
  4. debug = helper.debug
  5. load_input = helper.load_input
  6. CARD_VALUES = []
  7. for i in range(2,10):
  8. CARD_VALUES.append(str(i))
  9. CARD_VALUES.extend(["T", "J", "Q", "K", "A"])
  10. HAND_VALUES = [
  11. "High card",
  12. "One pair",
  13. "Two pair",
  14. "Three of a kind",
  15. "Full House",
  16. "Four of a kind",
  17. "Five of a kind"
  18. ]
  19. class Hand:
  20. def __init__(self, cards, bid):
  21. self.cards = cards
  22. self.bid = bid
  23. @property
  24. def value(self):
  25. card_counter = Counter(self.cards)
  26. card_counts = card_counter .most_common()
  27. if card_counts[0][1] == 5:
  28. return "Five of a kind"
  29. if card_counts[0][1] == 4:
  30. return "Four of a kind"
  31. if card_counts[0][1] == 3:
  32. if card_counts[1][1] == 2:
  33. return "Full House"
  34. return "Three of a kind"
  35. if card_counts[0][1] == 2:
  36. if card_counts[1][1] == 2:
  37. return "Two pair"
  38. return "One pair"
  39. return "High card"
  40. def __lt__(self, other):
  41. # They have different hand values
  42. if self.value != other.value:
  43. return HAND_VALUES.index(self.value) < HAND_VALUES.index(other.value)
  44. # They have the same hand value
  45. # So check each card in sequence
  46. for i in range(len(self.cards)):
  47. if self.cards[i] != other.cards[i]:
  48. # They have different nth cards
  49. return CARD_VALUES.index(self.cards[i]) < CARD_VALUES.index(other.cards[i])
  50. # They're the same
  51. return False
  52. def __str__(self):
  53. return f"Camel Cards hand: {self.cards} (value {self.value}, bid {self.bid})"
  54. def __repr__(self):
  55. return self.__str__()
  56. def main():
  57. lines = load_input(7)
  58. hands = []
  59. for line in lines:
  60. cards, bid = line.split()
  61. hands.append(Hand(
  62. cards = cards,
  63. bid = bid
  64. ))
  65. hands.sort()
  66. print(hands[:10])
  67. total_winnings = 0
  68. for i, hand in enumerate(hands):
  69. total_winnings += ((i+1) * int(hand.bid))
  70. print(f"Total winnings: {total_winnings}")
  71. if __name__ == "__main__":
  72. main()