-
Notifications
You must be signed in to change notification settings - Fork 0
/
day07.py
67 lines (47 loc) · 1.63 KB
/
day07.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Advent of Code 2024, Day 7: Bridge Repair.
See: https://adventofcode.com/2024/day/7
"""
import sys
from typing import TextIO
def parse(file: TextIO):
for line in file.read().splitlines():
value, operands = line.split(": ")
yield int(value), tuple(map(int, operands.split()))
def part_one(file: TextIO) -> int:
"""
Solve part one of the puzzle.
"""
def is_valid(value: int, operands: tuple[int, ...], current: int = 0):
if len(operands) == 0:
return current == value
head, *tail = operands
return is_valid(value, tail, current + head) or is_valid(
value, tail, current * head
)
return sum(value for value, operands in parse(file) if is_valid(value, operands))
def part_two(file: TextIO) -> int:
"""
Solve part two of the puzzle.
"""
def is_valid(value: int, operands: tuple[int, ...], current: int = 0):
if len(operands) == 0:
return current == value
head, *tail = operands
return (
is_valid(value, tail, current + head)
or is_valid(value, tail, current * head)
or is_valid(value, tail, int(str(current) + str(head)))
)
return sum(value for value, operands in parse(file) if is_valid(value, operands))
def main():
"""
The main entrypoint for the script.
"""
filename = sys.argv[0].replace(".py", ".txt")
with open(filename, encoding="utf-8") as file:
print("Part one:", part_one(file))
with open(filename, encoding="utf-8") as file:
print("Part two:", part_two(file))
if __name__ == "__main__":
main()