aoc24/day7/solution.py

37 lines
973 B
Python
Raw Normal View History

2024-12-08 23:06:44 +01:00
import sys
import itertools
def evaluate_expression(values, operators):
result = values[0]
for num, op in zip(values[1:], operators):
if op == "+":
result += num
elif op == "*":
result *= num
return result
def main():
lines = sys.stdin.read().splitlines()
valid_results = []
for line in lines:
target_result, raw_values = line.split(": ")
target_result = int(target_result)
numbers = list(map(int, raw_values.split()))
operators = ["*", "+"]
operator_combinations = itertools.product(operators, repeat=len(numbers) - 1)
for ops in operator_combinations:
try:
if evaluate_expression(numbers, ops) == target_result:
valid_results.append(target_result)
break
except Exception:
continue
return sum(valid_results)
if __name__ == "__main__":
print(main())