58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
from pathlib import Path
|
|
|
|
filepath = Path("./example")
|
|
filepath = Path("./input")
|
|
|
|
with open(filepath, "r") as filein:
|
|
data = [
|
|
(int(line.split(":")[0]), [int(b) for b in line.split(":")[1].split()])
|
|
for line in filein.readlines()
|
|
]
|
|
|
|
ops1 = {
|
|
"+": lambda a, b: a + b,
|
|
"*": lambda a, b: a * b,
|
|
}
|
|
|
|
ops2 = {
|
|
"+": lambda a, b: a + b,
|
|
# "-": lambda a, b: a - b,
|
|
"*": lambda a, b: a * b,
|
|
# "/": lambda a, b: a / b,
|
|
"|": lambda a, b: int(f"{a}{b}"),
|
|
}
|
|
|
|
|
|
def guess_operators(goal, operands, ops, operators=None):
|
|
if operators is None:
|
|
operators = ""
|
|
if len(operands) == 1:
|
|
return operands[0] == goal, operators
|
|
|
|
for k, f in ops.items():
|
|
first = f(*operands[:2])
|
|
new_operands = [first] + operands[2:]
|
|
test, result = guess_operators(goal, new_operands, ops, operators + k)
|
|
if test:
|
|
return test, result
|
|
else:
|
|
return False, result
|
|
|
|
|
|
def work_through_data(data, ops):
|
|
sum = 0
|
|
for goal, operands in data:
|
|
test, operations = guess_operators(goal, operands, ops)
|
|
if test:
|
|
calc = "".join([f"{a} {b} " for a, b in zip(operands, operations)]) + str(
|
|
operands[-1]
|
|
)
|
|
sum += goal
|
|
else:
|
|
calc = "impossible"
|
|
# print(goal, calc)
|
|
return sum
|
|
|
|
|
|
print(work_through_data(data, ops1))
|
|
print(work_through_data(data, ops2))
|