78 lines
2.2 KiB
Python
78 lines
2.2 KiB
Python
|
#!/bin/python3
|
||
|
import sys,re
|
||
|
from pprint import pprint
|
||
|
sys.path.insert(0, '../../')
|
||
|
from fred import list2int,get_re,nprint,lprint
|
||
|
|
||
|
input_f = 'input'
|
||
|
|
||
|
part = 2
|
||
|
#########################################
|
||
|
# #
|
||
|
# Part 1 #
|
||
|
# #
|
||
|
#########################################
|
||
|
|
||
|
def loadFile(input_f):
|
||
|
# For some reason, when this is a dict {}
|
||
|
# and i use instructions[int(a[0])] = list2int(b)
|
||
|
# the line with 360: 8 3 7 4 1 is not used in the
|
||
|
# for loop that runs through all the instructions.
|
||
|
|
||
|
instructions = []
|
||
|
|
||
|
with open(input_f) as file:
|
||
|
for line in file:
|
||
|
a = line.rstrip().split(': ')
|
||
|
b = a[1].split(' ')
|
||
|
|
||
|
instructions.append([int(a[0]),list2int(b)])
|
||
|
return instructions
|
||
|
|
||
|
|
||
|
|
||
|
if part == 1:
|
||
|
def calculateResult(a:int,b:list,result:int):
|
||
|
|
||
|
if not b:
|
||
|
return result if result == a else 0
|
||
|
|
||
|
add = calculateResult(a,b[1:],b[0]+result)
|
||
|
mul = calculateResult(a,b[1:],b[0]*result)
|
||
|
return add or mul
|
||
|
instructions = loadFile(input_f)
|
||
|
result = 0
|
||
|
|
||
|
for idx,i in enumerate(instructions):
|
||
|
result += calculateResult(instructions[idx][0],instructions[idx][1],0)
|
||
|
print(result)
|
||
|
|
||
|
|
||
|
#########################################
|
||
|
# #
|
||
|
# Part 2 #
|
||
|
# #
|
||
|
#########################################
|
||
|
if part == 2:
|
||
|
|
||
|
def calculateResult2(a:int,b:list,result:int):
|
||
|
|
||
|
if not b:
|
||
|
return result if result == a else 0
|
||
|
|
||
|
add = calculateResult2(a,b[1:],b[0]+result)
|
||
|
mul = calculateResult2(a,b[1:],b[0]*result)
|
||
|
# Issues happened when i did b[0]||result. Reversing it
|
||
|
# gave me the right result.
|
||
|
con = calculateResult2(a,b[1:],int(str(result)+str(b[0])))
|
||
|
return add or mul or con
|
||
|
|
||
|
instructions = loadFile(input_f)
|
||
|
result = 0
|
||
|
|
||
|
for idx,i in enumerate(instructions):
|
||
|
print('Line',(idx+1),i)
|
||
|
result += calculateResult2(instructions[idx][0],instructions[idx][1],0)
|
||
|
print(result)
|
||
|
|