adventofcode2024/day07/sol.py

35 lines
873 B
Python
Raw Normal View History

2024-12-07 05:43:17 +00:00
def solve(file):
t = 0
t2 = 0
for line in file:
nums = line.split()
goal = int(nums[0].rstrip(":"))
nums = [int(x) for x in nums[1:]]
if viable(goal, nums, lambda n,x: (n*x, n+x)):
2024-12-07 05:43:17 +00:00
t += goal
elif viable(goal, nums, lambda n,x: (n*x, n+x, int(str(n)+str(x)))):
2024-12-07 05:43:17 +00:00
t2 += goal
print(t)
print(t+t2)
def viable(goal, nums, combine):
2024-12-07 05:43:17 +00:00
candidates = [nums[0]]
for x in nums[1:-1]:
candidates = (lambda C, x: (
m
for n in C
for m in combine(n,x)
if m < goal
))(candidates, x)
#candidates = list(candidates); print(len(candidates))
x = nums[-1]
for n in candidates:
for m in combine(n,x):
if m == goal:
return True
return False
2024-12-07 05:43:17 +00:00
solve(open('sample1.in'))
solve(open('input'))