67 lines
1.4 KiB
Python
67 lines
1.4 KiB
Python
|
#!/usr/bin/env python
|
||
|
# 2023 - Advent Of Code 1 - part 2
|
||
|
|
||
|
# file = 'input_example2.txt'
|
||
|
file = 'input.txt'
|
||
|
|
||
|
text2num = [
|
||
|
("oneight", "1eight"),
|
||
|
("threeight", "3eight"),
|
||
|
("fiveight", "5eight"),
|
||
|
("nineight", "9eight"),
|
||
|
|
||
|
("eightwo", "8two"),
|
||
|
("eighthree", "8three"),
|
||
|
|
||
|
("twone", "2one"),
|
||
|
|
||
|
("sevenine", "7nine"),
|
||
|
|
||
|
("one", "1"),
|
||
|
("two", "2"),
|
||
|
("three", "3"),
|
||
|
("four", "4"),
|
||
|
("five", "5"),
|
||
|
("six", "6"),
|
||
|
("seven", "7"),
|
||
|
("eight", "8"),
|
||
|
("nine", "9")
|
||
|
]
|
||
|
|
||
|
|
||
|
def replace_text(lines_list):
|
||
|
print(lines_list)
|
||
|
replaced_lines = []
|
||
|
for line in lines_list:
|
||
|
tmp_line = line
|
||
|
for token in text2num:
|
||
|
tmp_line2 = tmp_line.replace(token[0], token[1])
|
||
|
tmp_line = tmp_line2
|
||
|
replaced_lines.append(tmp_line)
|
||
|
|
||
|
return replaced_lines
|
||
|
|
||
|
|
||
|
def num_and_sum(lines):
|
||
|
accum = 0
|
||
|
for line in lines:
|
||
|
first_num = last_num = -1
|
||
|
for c in line:
|
||
|
if '0' <= c <= '9':
|
||
|
if first_num == -1:
|
||
|
first_num = c
|
||
|
last_num = c
|
||
|
line_num = first_num + last_num
|
||
|
# print(f"first: {first_num}, last: {last_num}")
|
||
|
# print(f"line_num: {line_num}")
|
||
|
accum += int(line_num)
|
||
|
|
||
|
return accum
|
||
|
|
||
|
|
||
|
# pylint: disable=consider-using-with
|
||
|
input_lines = [line.strip('\n') for line in open(file, encoding="utf-8")]
|
||
|
new_lines = replace_text(input_lines)
|
||
|
# print(new_lines)
|
||
|
print(f"sum: {num_and_sum(new_lines)}")
|