-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.py
49 lines (40 loc) · 1.45 KB
/
day7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import itertools
import copy
# filename = 'day7sample.txt'
filename = 'day7.txt'
# Part One
fhand = open(filename)
testValues = list()
valueList = list()
for line in fhand:
testValues.append(int(line.strip().split(':')[0]))
lineVals = line.strip().split(':')[1].split()
lineVals = [int(x) for x in lineVals]
valueList.append(lineVals)
fhand.close()
def processEquation(vals,ops):
total = vals.pop(0)
for op in ops:
if op == '+': total = total + vals.pop(0)
if op == '*': total = total * vals.pop(0)
if op == '|': total = int(str(total) + str(vals.pop(0)))
return total
totalCalibrationList = list() # add to this list if it's valid
for i, val in enumerate(testValues):
operands = valueList[i]
operatorsSet = list(itertools.product('+*',repeat=len(operands)-1))
for operators in operatorsSet:
if val == processEquation(copy.deepcopy(operands),operators):
totalCalibrationList.append(val)
break
print('Part One Answer:', sum(totalCalibrationList))
# Part Two:
totalCalibrationList = list() # add to this list if it's valid
for i, val in enumerate(testValues):
operands = valueList[i]
operatorsSet = list(itertools.product('+*|',repeat=len(operands)-1))
for operators in operatorsSet:
if val == processEquation(copy.deepcopy(operands),operators):
totalCalibrationList.append(val)
break
print('Part Two Answer:', sum(totalCalibrationList))