Advertisement
hhoppe

Advent of code 2022 day 21

Dec 21st, 2022 (edited)
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. def day21(s, *, part2=False):  # Topological ordering for single-pass assignments.
  2.   dependencies, ops, assigned = {}, {}, {}
  3.   for line in s.splitlines():
  4.     dst, rest = line.split(': ')
  5.     if rest.isdigit():
  6.       assigned[dst] = int(rest)
  7.     else:
  8.       field0, op, field1 = rest.split()
  9.       dependencies[dst] = [field0, field1]
  10.       ops[dst] = op
  11.  
  12.   if part2:
  13.     del assigned['humn']
  14.     ops['root'] = '='
  15.  
  16.   # Assign nodes whose children are assigned.
  17.   import graphlib  # pylint: disable=import-error # Python 3.9.
  18.   for dst in graphlib.TopologicalSorter(dependencies).static_order():
  19.     if dep := dependencies.get(dst, None):
  20.       if dep[0] in assigned and dep[1] in assigned:
  21.         a, b, op = assigned[dep[0]], assigned[dep[1]], ops[dst]
  22.         assigned[dst] = (a + b if op == '+' else a - b if op == '-' else
  23.                          a * b if op == '*' else a // b)  # if op == '/'
  24.  
  25.   if not part2:
  26.     return assigned['root']
  27.  
  28.   # Trace a path from the root down, deriving the value of each unassigned node.
  29.   dst = 'root'
  30.   while dst != 'humn':
  31.     dep, op = dependencies[dst], ops[dst]
  32.     if dep[0] in assigned:
  33.       a = assigned[dep[0]]
  34.       value: int
  35.       value = (value - a if op == '+' else a - value if op == '-' else
  36.                value // a if op == '*' else a // value if op == '/' else a)
  37.       dst = dep[1]
  38.     else:
  39.       b = assigned[dep[1]]
  40.       value = (value - b if op == '+' else value + b if op == '-' else
  41.                value // b if op == '*' else value * b if op == '/' else b)
  42.       dst = dep[0]
  43.  
  44.   return value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement