Optimise day 1

This commit is contained in:
Sijmen 2023-12-01 14:46:18 +01:00
parent bd1cf6ffa0
commit f72708ca06
Signed by: vijfhoek
GPG key ID: DAF7821E067D9C48

36
day1.py
View file

@ -12,6 +12,7 @@ digit_map = {
"nine": 9, "nine": 9,
} }
digits = list(digit_map) digits = list(digit_map)
firstletters = set(s[0] for s in digits)
inp = list(fileinput.input()) inp = list(fileinput.input())
@ -19,13 +20,11 @@ inp = list(fileinput.input())
# Part 1 # Part 1
# #
part1 = sum( part1 = sum(
[ int(
int( next(x for x in line if x.isdigit())
next(x for x in y if x.isdigit()) + next(x for x in reversed(line) if x.isdigit())
+ next(x for x in reversed(y) if x.isdigit()) )
) for line in inp
for y in inp
]
) )
print(part1) print(part1)
@ -39,13 +38,30 @@ for line in inp:
newline = [] newline = []
for i in range(len(line)): for i in range(len(line)):
l = line[i:]
if line[i].isdigit():
newline.append(line[i])
break
for digit in digits: for digit in digits:
if line[i:].startswith(digit): if l.startswith(digit):
newline.append(str(digit_map[digit])) newline.append(str(digit_map[digit]))
break break
else: else:
if line[i].isdigit(): continue
newline.append(line[i]) 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]) part2 += int(newline[0] + newline[-1])