#!/usr/bin/env python from functools import cache from collections import defaultdict import operator ops = { 'EQ': lambda x: x, 'NOT': lambda x: ~x & 0xffff, 'AND': operator.iand, 'OR': operator.ior, 'RSHIFT': operator.rshift, 'LSHIFT': operator.lshift } wires = defaultdict(list) with open('day7.txt') as data: for line in data: calc, target = line.strip().split(' -> ') calc = calc.split() if len(calc) == 1: wires[target] = ('EQ', calc[0]) elif len(calc) == 2: wires[target] = (calc[0], calc[1]) else: wires[target] = (calc[1], calc[0], calc[2]) @cache def get_value(key): try: return int(key) except ValueError: pass op, *value = wires[key] if len(value) == 1: return ops[op](get_value(value[0])) else: return ops[op](get_value(value[0]), get_value(value[1])) # part 1 print(get_value('a')) # part 2 get_value.cache_clear() wires['b'] = ('EQ', 3176) print(get_value('a'))