68 lines
1.2 KiB
Python
68 lines
1.2 KiB
Python
import fileinput
|
|
|
|
digit_map = {
|
|
"one": 1,
|
|
"two": 2,
|
|
"three": 3,
|
|
"four": 4,
|
|
"five": 5,
|
|
"six": 6,
|
|
"seven": 7,
|
|
"eight": 8,
|
|
"nine": 9,
|
|
}
|
|
digits = list(digit_map)
|
|
firstletters = set(s[0] for s in digits)
|
|
|
|
inp = list(fileinput.input())
|
|
|
|
#
|
|
# Part 1
|
|
#
|
|
part1 = sum(
|
|
int(
|
|
next(x for x in line if x.isdigit())
|
|
+ next(x for x in reversed(line) if x.isdigit())
|
|
)
|
|
for line in inp
|
|
)
|
|
|
|
print(part1)
|
|
|
|
#
|
|
# Part 2
|
|
#
|
|
part2 = 0
|
|
|
|
for line in inp:
|
|
newline = []
|
|
|
|
for i in range(len(line)):
|
|
l = line[i:]
|
|
if line[i].isdigit():
|
|
newline.append(line[i])
|
|
break
|
|
for digit in digits:
|
|
if l.startswith(digit):
|
|
newline.append(str(digit_map[digit]))
|
|
break
|
|
else:
|
|
continue
|
|
break
|
|
|
|
for i in reversed(range(len(line))):
|
|
l = line[i:]
|
|
if line[i].isdigit():
|
|
newline.append(line[i])
|
|
break
|
|
for digit in digits:
|
|
if l.startswith(digit):
|
|
newline.append(str(digit_map[digit]))
|
|
break
|
|
else:
|
|
continue
|
|
break
|
|
|
|
part2 += int(newline[0] + newline[-1])
|
|
|
|
print(part2)
|