-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07.py
50 lines (35 loc) · 1.22 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
INPUT = 'input'
def main():
equations = [parse(line) for line in read().splitlines()]
ans1 = sum(
result
for result, operands in equations
if any(result == value for value in variations(operands, False)))
ans2 = sum(
result
for result, operands in equations
if any(result == value for value in variations(operands, True)))
print(f'Part 1: {ans1}\nPart 2: {ans2}')
def concatenate(a, b):
factor = 10
while b // factor:
factor *= 10
return a * factor + b
def variations(operands, include_concatenate=False):
[*rest, operand] = operands
if not rest:
yield operand
else:
yield from (
result
for variation in variations(rest, include_concatenate)
for result in ((variation + operand, variation * operand, concatenate(variation, operand))
if include_concatenate
else (variation + operand, variation * operand))
)
def parse(line):
(test_value, *operands) = [int(part.strip(':')) for part in line.split(' ')]
return test_value, operands
def read():
return open(f'./input/2024/day07/{INPUT}.txt').read().strip()
main()