Advertisement
hhoppe

Advent of code 2024 day 7

Dec 7th, 2024 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. def day7(s, part2=False):
  2.   total = 0
  3.   for line in s.splitlines():
  4.     desired, *values = map(int, re.split(':? ', line))
  5.  
  6.     def count_digits(number):
  7.       return 1 if number == 0 else math.floor(math.log10(abs(number))) + 1
  8.  
  9.     def can_eval(current, lst):
  10.       if not lst:
  11.         return current == desired
  12.       if current > desired:  # Optional pruning speedup (from 2.9 s to 1.9 s).
  13.         return False
  14.       return (
  15.           can_eval(current * lst[0], lst[1:])
  16.           or can_eval(current + lst[0], lst[1:])
  17.           or (part2 and can_eval(current * 10 ** count_digits(lst[0]) + lst[0], lst[1:]))
  18.       )
  19.  
  20.     if can_eval(values[0], values[1:]):
  21.       total += desired
  22.  
  23.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement