Created
December 7, 2015 21:01
-
-
Save boxdot/5fac10cec21258cafab5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parse(line, data): | |
incom, outName = line.split(" -> ") | |
tokens = incom.split(" ") | |
if len(tokens) == 1: | |
try: | |
val = int(tokens[0]) | |
data[outName] = val | |
except Exception: | |
data[outName] = tokens[0] | |
elif len(tokens) == 2: | |
data[outName] = (tokens[1], lambda x: ~x) | |
elif len(tokens) == 3: | |
a, op, b = tokens[:3] | |
if op == "AND": | |
try: | |
val = int(tokens[0]) | |
data[outName] = (b, lambda x: val & x) | |
except Exception: | |
data[outName] = (a, b, lambda x, y: x & y) | |
elif op == "OR": | |
data[outName] = (a, b, lambda x, y: x ^ y) | |
elif op == "RSHIFT": | |
num = int(b) | |
data[outName] = (a, lambda x: x >> num) | |
elif op == "LSHIFT": | |
num = int(b) | |
data[outName] = (a, lambda x: x << num) | |
def connect(out, data, computed): | |
if out in computed: | |
return computed[out] | |
incom = data[out] | |
if type(incom) is int: | |
computed[out] = incom | |
return incom | |
elif type(incom) is not tuple: | |
computed[out] = connect(incom, data, computed) | |
return computed[out] | |
elif len(incom) == 2: | |
a = connect(incom[0], data, computed) | |
computed[out] = incom[1](a) | |
return computed[out] | |
elif len(incom) == 3: | |
a = connect(incom[0], data, computed) | |
b = connect(incom[1], data, computed) | |
computed[out] = incom[2](a, b) | |
return computed[out] | |
lines = open("day7.input").read().split("\n") | |
data = {} | |
map(lambda l: parse(l, data), lines) | |
print connect("a", data, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment