49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
|
import fileinput
|
||
|
from collections import deque
|
||
|
|
||
|
|
||
|
input = []
|
||
|
for line in fileinput.input():
|
||
|
expression, wire = line.strip().split(" -> ")
|
||
|
input.append((expression.split(), wire))
|
||
|
|
||
|
|
||
|
def simulate(wires):
|
||
|
def get(signal):
|
||
|
if signal.isdigit():
|
||
|
return int(signal)
|
||
|
else:
|
||
|
return wires[signal]
|
||
|
|
||
|
queue = deque(input)
|
||
|
while queue:
|
||
|
expression, wire = queue.popleft()
|
||
|
if wire in wires:
|
||
|
continue
|
||
|
|
||
|
try:
|
||
|
match expression:
|
||
|
case [signal]:
|
||
|
wires[wire] = get(signal)
|
||
|
case ["NOT", signal]:
|
||
|
wires[wire] = ~get(signal)
|
||
|
case [left, "AND", right]:
|
||
|
wires[wire] = get(left) & get(right)
|
||
|
case [left, "OR", right]:
|
||
|
wires[wire] = get(left) | get(right)
|
||
|
case [left, "LSHIFT", right]:
|
||
|
wires[wire] = get(left) << get(right)
|
||
|
case [left, "RSHIFT", right]:
|
||
|
wires[wire] = get(left) >> get(right)
|
||
|
except KeyError:
|
||
|
queue.append((expression, wire))
|
||
|
|
||
|
return wires["a"]
|
||
|
|
||
|
|
||
|
part1 = simulate({})
|
||
|
print("part 1:", part1)
|
||
|
|
||
|
part2 = simulate({"b": part1})
|
||
|
print("part 2:", part2)
|