File size: 1,058 Bytes
a4da721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from itertools import product

def evaluate_expression(numbers, operators):
    result = numbers[0]
    for i, op in enumerate(operators):
        if op == '+':
            result += numbers[i + 1]
        elif op == '*':
            result *= numbers[i + 1]
        elif op == '||':
            result = int(str(result) + str(numbers[i + 1]))
    return result

def is_valid_equation(test_value, numbers):
    num_operators = len(numbers) - 1
    for ops in product(['+', '*', '||'], repeat=num_operators):
        if evaluate_expression(numbers, ops) == test_value:
            return True
    return False

def main():
    total_calibration_result = 0
    with open("input.txt", "r") as file:
        for line in file:
            test_value_str, numbers_str = line.split(':')
            test_value = int(test_value_str.strip())
            numbers = list(map(int, numbers_str.split()))
            
            if is_valid_equation(test_value, numbers):
                total_calibration_result += test_value

    print(total_calibration_result)

main()