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
|
#advent of code 2024
#day 07
#rewritten to do both parts at the same time
#very slow solution (roughly 10 mins of runtime)
#it generates all possible arrangements of operators
#to fill in the empty spaces in the equation
#on top of that, it utilizes eval()
#however, the solution works and that's the important part
import itertools
def calculate(test,nums,ops):
N = [n for n in nums.split(" ")];
ValidAnswerP1 = False;
ValidAnswerP2 = False;
for prod in itertools.product(ops,repeat=nums.count(" ")):
score = ''+N[0];
for i,p in enumerate(prod):
if p == "||": p = "";
teststring = str(score) + p + N[i+1];
score = eval(teststring);
if score == test:
ValidAnswerP2 = True;
if "||" not in prod: ValidAnswerP1 = True;
if ValidAnswerP1 and ValidAnswerP2: break;
return ValidAnswerP1, ValidAnswerP2;
part1 = 0;
part2 = 0;
ops = ["+","*","||"];
f = open("07.ex","r");
for l in f:
TestValue, numbers = l[:-1].split(": ");
TestValue = int(TestValue);
valid_p1, valid_p2 = calculate(TestValue, numbers,ops);
part1 += valid_p1*TestValue;
part2 += valid_p2*TestValue;
f.close();
print("part 1 = ", part1);
print("part 2 = ", part2);
|