Spaces:
Running
Running
def parse_input(filename): | |
equations = [] | |
with open(filename, 'r') as f: | |
for line in f: | |
test_value, numbers = line.strip().split(': ') | |
test_value = int(test_value) | |
numbers = [int(x) for x in numbers.split()] | |
equations.append((test_value, numbers)) | |
return equations | |
def evaluate(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 try_all_combinations(test_value, numbers, operators_set): | |
if len(numbers) == 1: | |
return test_value == numbers[0] | |
n = len(numbers) - 1 # number of operators needed | |
for ops in itertools.product(operators_set, repeat=n): | |
if evaluate(numbers, ops) == test_value: | |
return True | |
return False | |
import itertools | |
def solve_part1(equations): | |
total = 0 | |
operators = ['+', '*'] | |
for test_value, numbers in equations: | |
if try_all_combinations(test_value, numbers, operators): | |
total += test_value | |
return str(total) | |
def solve_part2(equations): | |
total = 0 | |
operators = ['+', '*', '||'] | |
for test_value, numbers in equations: | |
if try_all_combinations(test_value, numbers, operators): | |
total += test_value | |
return str(total) | |
# Read input and solve both parts | |
equations = parse_input("./input.txt") | |
print(solve_part1(equations)) | |
print(solve_part2(equations)) |