37 lines
973 B
Python
37 lines
973 B
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
|
||
|
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())
|