-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7_p2.py
53 lines (38 loc) · 1.37 KB
/
day7_p2.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
50
51
52
import itertools
import math
def merge(l, r):
# Concatenate l and r as strings and convert back to int
return int(str(l) + str(r))
def evaluate_expression(operands, operators):
result = operands[0]
for i in range(1, len(operands)):
if operators[i-1] == '+':
result += operands[i]
elif operators[i-1] == '*':
result *= operands[i]
elif operators[i-1] == '||':
result = merge(result, operands[i])
return result
def generate_operator_combinations(num_operands):
operators = ['+', '*', '||']
return itertools.product(operators, repeat=num_operands - 1)
def is_valid_equation(test_value, operands):
num_operands = len(operands)
for operator_combo in generate_operator_combinations(num_operands):
result = evaluate_expression(operands, operator_combo)
if result == test_value:
return True
return False
def process_input(input_data):
total_sum = 0
for line in input_data:
left, right = line.split(": ")
test_value = int(left)
operands = list(map(int, right.split()))
if is_valid_equation(test_value, operands):
total_sum += test_value
return total_sum
#with open("test.txt", "r") as file:
with open("input_day7_p1.txt", "r") as file:
input_data = file.readlines()
print(process_input(input_data))