-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.py
56 lines (46 loc) · 1.48 KB
/
day7.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
import time
start_time = time.time()
day = 7
is_test = False
# --- Day 7: Bridge Repair ---
def read_input():
targets = []
nums = []
with open(f'./input/day{day}{"_test" if is_test else ""}.txt') as file:
for line in file:
target, ns = line.strip().split(':')
targets.append(int(target.strip()))
nums.append([int(n) for n in ns.strip().split()])
return targets, nums
ops0 = '+*'
ops1 = '+*|'
def sol(targets, all_nums):
def calc(target, total, idx, ops, nums):
if idx >= len(nums):
return total == target
for op in ops:
if op == '+':
t = total + nums[idx]
if calc(target, t, idx + 1, ops, nums):
return True
elif op == '*':
t = total * nums[idx]
if calc(target, t, idx + 1, ops, nums):
return True
elif op == '|':
t = int(str(total) + str(nums[idx]))
if calc(target, t, idx + 1, ops, nums):
return True
return False
total0 = 0
total1 = 0
for target, ns in zip(targets, all_nums):
if calc(target, ns[0], 1, ops0, ns):
total0 += target
if calc(target, ns[0], 1, ops1, ns):
total1 += target
return total0, total1
if __name__ == "__main__":
targets, nums = read_input()
print(sol(targets, nums))
print(f'time = {(time.time() - start_time):.6f}s')