Advertisement
Guest User

Untitled

a guest
Dec 20th, 2023
1,149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. def make_trie (word_array):
  2.     trie = {}
  3.     current = None
  4.  
  5.     for i in range(len(word_array)):
  6.         current = trie
  7.         for c in word_array[i]:
  8.             if c not in current:
  9.                 current[c] = {}
  10.             current = current[c]
  11.  
  12.         current["value"] = i + 1
  13.  
  14.  
  15.     return trie
  16.  
  17. def parse_line(line):
  18.    
  19.     english_numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
  20.     root = make_trie(english_numbers)
  21.  
  22.     result = ""
  23.     current_node = root
  24.     last_char = ''
  25.  
  26.  
  27.     for c in line:
  28.  
  29.         # Literal number
  30.         if c.isnumeric():
  31.             result += c
  32.             current_node = root
  33.             continue
  34.  
  35.         print("Char {} --> ".format(c))
  36.         if c in current_node:
  37.             # current char is the follow up to the last character
  38.             current_node = current_node[c]
  39.         else:
  40.             # last char is not follow up
  41.             if last_char in root and c in root[last_char]:
  42.                 # ... but last char is a starting char and current char is a follow up
  43.                 # eightwo case
  44.                 current_node = root[last_char][c]
  45.  
  46.             elif c in root:
  47.                 # ... current char is not a follow up to anything but is a starting char
  48.                 current_node = root[c]
  49.  
  50.  
  51.         if 'value' in current_node:
  52.             result += repr(current_node['value'])
  53.  
  54.  
  55.         last_char = c
  56.        
  57.  
  58.  
  59.  
  60.     return result
  61.  
  62. def get_calibration(line):
  63.     numbers = parse_line(line)
  64.     if len(numbers) == 1:
  65.         num = int(numbers[0] + numbers[0])
  66.     else:
  67.         num = int(numbers[0] + numbers[-1])
  68.     return num
  69.  
  70. def main():
  71.     total = 0
  72.  
  73.     with open("input.txt", 'r') as inf:
  74.         for line in inf:
  75.             total += get_calibration(line)
  76.  
  77.     print(total)
  78.  
  79. if __name__ == "__main__":
  80.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement