Advertisement
Guest User

Advent of Code 2023 - Day 1

a guest
Dec 1st, 2023
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. from string import digits
  2.  
  3. NUM_STR_MAP = {
  4.     "one": "1",
  5.     "two": "2",
  6.     "three": "3",
  7.     "four": "4",
  8.     "five": "5",
  9.     "six": "6",
  10.     "seven": "7",
  11.     "eight": "8",
  12.     "nine": "9",
  13. }
  14.  
  15. STR_INT_MAP = {str(i): i for i in range(1, 10)}
  16.  
  17. NUM_CHARS = set(digits)
  18. NUM_STRS = set(NUM_STR_MAP.keys())
  19.  
  20. input_data = """..."""
  21.  
  22. part_a_test_data = """1abc2
  23. pqr3stu8vwx
  24. a1b2c3d4e5f
  25. treb7uchet"""
  26.  
  27.  
  28. def part_a(data):
  29.     total = 0
  30.     for row in data.split("\n"):
  31.         nums = [c for c in row if c in NUM_CHARS]
  32.         total += int(nums[0] + nums[-1])
  33.     return total
  34.  
  35.  
  36. def make_trie(words):
  37.     root = dict()
  38.     for word in words:
  39.         current_dict = root
  40.         for letter in word:
  41.             current_dict = current_dict.setdefault(letter, {})
  42.     return root
  43.  
  44.  
  45. part_b_test_data = """two1nine
  46. eightwothree
  47. abcone2threexyz
  48. xtwone3four
  49. 4nineeightseven2
  50. zoneight234
  51. 7pqrstsixteen"""
  52.  
  53.  
  54. def part_b(data):
  55.     total = 0
  56.     numbers = [*NUM_STR_MAP.values(), *NUM_STR_MAP.keys()]
  57.     trie = make_trie(numbers)
  58.     for word in data.splitlines():
  59.         word_len = len(word)
  60.         word_numbers = []
  61.         for i in range(len(word)):
  62.             j = i
  63.             current_str = ""
  64.             current = trie
  65.             if word[j] not in current:
  66.                 i += 1
  67.                 continue
  68.             while j < word_len:
  69.                 if word[j] not in current:
  70.                     i += 1
  71.                     break
  72.                 current_str += word[j]
  73.                 if not current[word[j]]:
  74.                     if len(current_str) == 1:
  75.                         word_numbers.append(current_str)
  76.                     else:
  77.                         word_numbers.append(NUM_STR_MAP[current_str])
  78.                     i += 1
  79.                     break
  80.                 else:
  81.                     current = current[word[j]]
  82.                     j += 1
  83.         number_str = word_numbers[0] + word_numbers[-1]
  84.         total += int(number_str)
  85.     return total
  86.  
  87.  
  88. if __name__ == "__main__":
  89.     print(part_a(data=part_a_test_data))  # 142
  90.     print(part_a(data=input_data))
  91.     print(part_b(part_b_test_data))  # 281
  92.     print(part_b(data=input_data))
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement