46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
with open('puzzle.txt', 'r') as f:
|
|
lines = f.read().splitlines()
|
|
|
|
import operator
|
|
|
|
operations = {
|
|
0: operator.add,
|
|
1: operator.mul
|
|
}
|
|
|
|
def operator_increment(depth, result, value_list, operator_list, operation_list):
|
|
for calc_operator in operator_list:
|
|
if depth == 0:
|
|
calc = value_list[0]
|
|
for index, value in enumerate(value_list[:-1]):
|
|
calc = operator_list[operation_list[-index]](calc, value_list[index + 1])
|
|
|
|
if calc == result:
|
|
return True, calc
|
|
|
|
else:
|
|
operation_list[depth - 1] = calc_operator
|
|
return_status, calc = operator_increment(depth - 1, result, value_list, operator_list, operation_list)
|
|
if return_status:
|
|
return return_status, calc
|
|
|
|
return False, 0
|
|
|
|
values = {}
|
|
|
|
for line in lines:
|
|
test_value, equation_values = line.split(':')
|
|
test_value = int(test_value)
|
|
equation_values = list(map(int, equation_values.strip().split(' ')))
|
|
values.update({test_value: equation_values})
|
|
|
|
total_calibration = 0
|
|
|
|
for result in values:
|
|
operation_list = [None] * (len(values[result]) - 1)
|
|
return_status, calc = operator_increment(len(values[result])-1, result, values[result], operations, operation_list)
|
|
if return_status:
|
|
total_calibration += calc
|
|
|
|
print(total_calibration)
|