from itertools import product file = 'in' ans_1= 0 ans_2= 0 def app(orig, v): if orig == '0': return v return orig+v def mult(orig,v): v = v.replace('*','') x = int(orig)*int(v) return str(x) def div(orig,v): v = v.replace('/','') x = int(orig)//int(v) return str(x) def repl(orig,v): v1,v2 = v.split('->') return orig.replace(v1,v2) def bksp(orig,_): if orig == '0' or len(orig) == 1: return '0' return orig[:-1] def oct_r(orig,_): o = int(orig) v = '' if o == 0: return '0' while o > 0: v = v + str(o%8) o = o//8 return ''.join(list(reversed(v))) def nothing(orig,_): return orig funcs = (mult,div,repl,bksp,oct_r,nothing) data = open(file).read().strip().split() data = [x.replace('[','').replace(']','') for x in data] data.append('') funcs_with_instr = set() for instr in data: checks = ( '*' in instr, '/' in instr, '->' in instr, 'bksp' in instr, 'oct' in instr, instr == '' ) if any(checks): func = funcs[[i for i in range(len(checks)) if checks[i]][0]] else: func = app funcs_with_instr.add((func,instr)) combs = list(set(product(funcs_with_instr,repeat=3))) seen = set() for combo in combs: curr = '0' for instr in combo: curr = instr[0](curr,instr[1]) if curr not in seen: seen.add(curr) ans_1 += int(curr) print(f"SOLUTION FOR PART1: {ans_1}") seen = set() start = [f[0]('0', f[1]) for f in funcs_with_instr] for o in range(9999): curr = list(start) while curr: n = curr.pop() if n not in seen: if n == str(o): ans_2 += int(o) seen.add(n) elif int(n) <= 9999: ans_2 += int(n) seen.add(n) curr.extend([f[0](n,f[1]) for f in funcs_with_instr if f[0](n,f[1]) not in seen]) print(f"SOLUTION FOR PART2: {ans_2}")