38 lines
1 KiB
Python
38 lines
1 KiB
Python
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
|
|
elif op == "||":
|
|
result = int(str(result) + str(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())
|