1
0
Fork 0

Iterative solution for December 7th 2015

This commit is contained in:
Lucidiot 2018-10-11 22:24:53 +02:00
parent e6a2fa044d
commit 894f3a5f4f
No known key found for this signature in database
GPG Key ID: AE3F7205692FA205
1 changed files with 59 additions and 0 deletions

59
2015/7/iterative_wire.py Executable file
View File

@ -0,0 +1,59 @@
#!/usr/bin/env python3
import sys
from pprint import pprint
wires = {}
instructions = [l.strip().split(' -> ') for l in sys.stdin.readlines()]
instructions = [(instruction.split(' '), dest) for instruction, dest in instructions]
def get_value(text):
if text.isdigit():
return int(text)
return wires.get(text)
def parse(line):
words, dest = line
if len(words) == 1:
if words[0].isdigit() and dest in wires:
print('Ignoring redefinition of wire {} to {} (already set to {})'.format(
dest, words[0], wires[dest]))
return False
value = get_value(words[0])
if value is None:
return True
wires[dest] = value
return False
elif len(words) == 2 and words[0] == 'NOT':
value = get_value(words[1])
if value is None:
return True
wires[dest] = ~value & 0xffff
return False
elif len(words) == 3:
a, gate, b = words
a, b = get_value(a), get_value(b)
if a is None or b is None:
return True
if gate == 'AND':
wires[dest] = a & b
elif gate == 'OR':
wires[dest] = a | b
elif gate == 'LSHIFT':
wires[dest] = a << b
elif gate == 'RSHIFT':
wires[dest] = a >> b
else:
raise NotImplementedError
return False
else:
raise NotImplementedError
def find_wire(name, data):
while name not in wires:
data = list(filter(parse, data))
return wires[name]
part_one = find_wire('a', instructions)
print('Part 1:', part_one)
wires = {'b': part_one}
part_two = find_wire('a', instructions)
print('Part 2:', part_two)