adventofcode/2023/day1/main.py

37 lines
995 B
Python
Raw Normal View History

2023-12-02 04:02:42 +01:00
import re
def part1(file):
acc = []
with open(file) as f:
for line in f:
digits = [match for match in re.findall(r"\d", line)]
acc.append(int(f"{digits[0]}{digits[-1]}"))
return sum(acc)
def part2(file):
numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
acc = []
with open(file) as f:
for line in f:
line = re.sub(
"|".join(f"(?=({number}))" for number in numbers),
lambda match: str(
numbers.index([i for i in match.groups() if i is not None][0]) + 1
),
line,
)
digits = [match for match in re.findall(r"\d", line)]
acc.append(int(f"{digits[0]}{digits[-1]}"))
return sum(acc)
if __name__ == "__main__":
assert part1("example_part1.txt") == 142
print(part1("input.txt"))
assert part2("example_part2.txt") == 281
print(part2("input.txt"))