Skip to content

Instantly share code, notes, and snippets.

@jongyllen
Created December 7, 2024 11:40
Show Gist options
  • Select an option

  • Save jongyllen/305a39cef2c39e7b0f34b28a07da2bfc to your computer and use it in GitHub Desktop.

Select an option

Save jongyllen/305a39cef2c39e7b0f34b28a07da2bfc to your computer and use it in GitHub Desktop.
def evaluate_expression(nums, ops):
r = nums[0]
for i, op in enumerate(ops):
if op == '+': r += nums[i + 1]
elif op == '*': r *= nums[i + 1]
else: r = r * (10 ** len(str(nums[i + 1]))) + nums[i + 1]
return r
def can_make_equation_part1(tv, nums):
def try_combs(pos, ops):
if pos == len(nums) - 1: return evaluate_expression(nums, ops) == tv
for op in ['+', '*']:
ops.append(op)
if try_combs(pos + 1, ops): return True
ops.pop()
return False
return try_combs(0, [])
def can_make_equation_part2(tv, nums):
def try_combs(pos, ops, curr):
if pos == len(nums) - 1: return curr == tv
n = nums[pos + 1]
for op, fn in [('+', lambda x,y: x+y), ('*', lambda x,y: x*y),
('||', lambda x,y: x*(10**len(str(y)))+y)]:
ops.append(op)
if (new := fn(curr, n)) <= tv and try_combs(pos + 1, ops, new): return True
ops.pop()
return False
return try_combs(0, [], nums[0])
def solve_calibration(data, part2=False):
return sum(tv for line in data.strip().split('\n')
if (tv := int(line.split(': ')[0]))
and (can_make_equation_part2 if part2 else can_make_equation_part1)
(tv, [int(x) for x in line.split(': ')[1].split()]))
if __name__ == "__main__":
try:
with open('day7.data') as f:
data = f.read()
for part2 in [False, True]:
print(f"Part {1 if not part2 else 2}: {solve_calibration(data, part2)}")
except FileNotFoundError:
print("Error: day7.data not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment