36 lines
995 B
Python
36 lines
995 B
Python
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"))
|