59 lines
1.2 KiB
Python
59 lines
1.2 KiB
Python
|
#!/usr/bin/env python
|
||
|
# -*- encoding: utf-8; py-indent-offset: 4 -*-
|
||
|
|
||
|
# Author: Sebastian Mark
|
||
|
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
|
||
|
|
||
|
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
|
||
|
|
||
|
import re
|
||
|
|
||
|
|
||
|
def readinput():
|
||
|
with open("input", "r", encoding="utf-8") as file:
|
||
|
lines = file.readlines()
|
||
|
return lines
|
||
|
|
||
|
|
||
|
def get_number(line: str) -> int:
|
||
|
regex = r"\d"
|
||
|
matches = re.findall(regex, line)
|
||
|
new_number = matches[0] + matches[-1]
|
||
|
return int(new_number)
|
||
|
|
||
|
|
||
|
def get_spelled_number(line: str) -> int:
|
||
|
number_map = {
|
||
|
"one": "o1e",
|
||
|
"two": "t2o",
|
||
|
"three": "t3e",
|
||
|
"four": "f4r",
|
||
|
"five": "f5e",
|
||
|
"six": "s6x",
|
||
|
"seven": "s7n",
|
||
|
"eight": "e8t",
|
||
|
"nine": "n9e",
|
||
|
}
|
||
|
|
||
|
for k, v in number_map.items():
|
||
|
if k in line:
|
||
|
line = line.replace(k, v)
|
||
|
|
||
|
return get_number(line)
|
||
|
|
||
|
|
||
|
def main():
|
||
|
lines = readinput()
|
||
|
|
||
|
# part1
|
||
|
count = sum(get_number(line) for line in lines)
|
||
|
print("Sum: %d" % count)
|
||
|
|
||
|
# part1
|
||
|
count = sum(get_spelled_number(line) for line in lines)
|
||
|
print("Sum (literals): %d" % count)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|