Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def make_trie (word_array):
- trie = {}
- current = None
- for i in range(len(word_array)):
- current = trie
- for c in word_array[i]:
- if c not in current:
- current[c] = {}
- current = current[c]
- current["value"] = i + 1
- return trie
- def parse_line(line):
- english_numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
- root = make_trie(english_numbers)
- result = ""
- current_node = root
- last_char = ''
- for c in line:
- # Literal number
- if c.isnumeric():
- result += c
- current_node = root
- continue
- print("Char {} --> ".format(c))
- if c in current_node:
- # current char is the follow up to the last character
- current_node = current_node[c]
- else:
- # last char is not follow up
- if last_char in root and c in root[last_char]:
- # ... but last char is a starting char and current char is a follow up
- # eightwo case
- current_node = root[last_char][c]
- elif c in root:
- # ... current char is not a follow up to anything but is a starting char
- current_node = root[c]
- if 'value' in current_node:
- result += repr(current_node['value'])
- last_char = c
- return result
- def get_calibration(line):
- numbers = parse_line(line)
- if len(numbers) == 1:
- num = int(numbers[0] + numbers[0])
- else:
- num = int(numbers[0] + numbers[-1])
- return num
- def main():
- total = 0
- with open("input.txt", 'r') as inf:
- for line in inf:
- total += get_calibration(line)
- print(total)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement