You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
2.4 KiB
55 lines
2.4 KiB
import time
|
|
start = time.time()
|
|
file = open('input.txt', 'r')
|
|
commands = {}
|
|
cached_output = {}
|
|
def string_or_int(value):
|
|
if value.isdigit(): return int(value)
|
|
else: return value
|
|
|
|
def parse_command(output, operator, string):
|
|
splits = string.split(" ")
|
|
commands[output] = {}
|
|
commands[output]['operator'] = operator
|
|
if operator == "ASSIGN":
|
|
commands[output]['value_1'] = string_or_int(splits[0])
|
|
elif operator == "NOT":
|
|
commands[output]['value_1'] = string_or_int(splits[1])
|
|
elif operator == "AND" or operator == "OR" or operator == "LSHIFT" or operator == "RSHIFT":
|
|
commands[output]['value_1'] = string_or_int(splits[0])
|
|
commands[output]['value_2'] = string_or_int(splits[2])
|
|
|
|
for line in file:
|
|
splits = line.split(" ")
|
|
output = splits[len(splits)-1]
|
|
output = output.strip()
|
|
if line.find("NOT") != -1: parse_command(output, "NOT", line)
|
|
elif line.find("AND") != -1: parse_command(output, "AND", line)
|
|
elif line.find("OR") != -1: parse_command(output, "OR", line)
|
|
elif line.find("LSHIFT") != -1: parse_command(output, "LSHIFT", line)
|
|
elif line.find("RSHIFT") != -1: parse_command(output, "RSHIFT", line)
|
|
else: parse_command(output, "ASSIGN", line)
|
|
|
|
def calc_and_cache_output(key):
|
|
if isinstance( key, int ): cached_output[key] = key
|
|
else: cached_output[key] = calc_output(key)
|
|
return cached_output[key]
|
|
|
|
def calc_output(key):
|
|
if key in cached_output: return cached_output[key]
|
|
command = commands[key]
|
|
operator = command['operator']
|
|
if operator == "ASSIGN": return calc_and_cache_output(command['value_1'])
|
|
elif operator == "NOT": return ~calc_and_cache_output(command['value_1'])
|
|
elif operator == "AND": return calc_and_cache_output(command['value_1']) & calc_and_cache_output(command['value_2'])
|
|
elif operator == "OR": return calc_and_cache_output(command['value_1']) | calc_and_cache_output(command['value_2'])
|
|
elif operator == "LSHIFT": return calc_and_cache_output(command['value_1']) << calc_and_cache_output(command['value_2'])
|
|
elif operator == "RSHIFT": return calc_and_cache_output(command['value_1']) >> calc_and_cache_output(command['value_2'])
|
|
|
|
value = calc_output('a')
|
|
print("Value of a is: " + str(value))
|
|
cached_output = {}
|
|
cached_output['b'] = value
|
|
value = calc_output('a')
|
|
print("Value of a is: " + str(value))
|
|
print(time.time() - start)
|