67 lines
1.6 KiB
Python
67 lines
1.6 KiB
Python
import re
|
|
|
|
with open('input.text', 'r') as file:
|
|
data: list[str] = file.readlines()
|
|
|
|
|
|
class Equation:
|
|
result: int
|
|
constants: list[int]
|
|
|
|
def __init__(self, result: int, constants: list[int]):
|
|
self.result = result
|
|
self.constants = constants
|
|
|
|
def is_valid_eq(self, eq: str) -> bool:
|
|
tokens: list[str] = re.findall('\d+|\+|\*', eq)
|
|
|
|
r = None
|
|
add = True
|
|
for token in tokens:
|
|
if not r and token.isnumeric():
|
|
r = int(token)
|
|
elif token == '+':
|
|
add = True
|
|
elif token == '*':
|
|
add = False
|
|
elif add:
|
|
r += int(token)
|
|
elif not add:
|
|
r *= int(token)
|
|
|
|
return r == self.result
|
|
|
|
def is_valid(self, s: str | None) -> bool:
|
|
if s == None:
|
|
s = ''
|
|
for c in self.constants:
|
|
s += (str(c) + ' ')
|
|
return self.is_valid(s[:-1])
|
|
elif ' ' in s:
|
|
s1 = s.replace(' ', '+', 1)
|
|
s2 = s.replace(' ', '*', 1)
|
|
return self.is_valid(s1) or self.is_valid(s2)
|
|
else:
|
|
return self.is_valid_eq(s)
|
|
|
|
|
|
equations: list[Equation] = []
|
|
|
|
# Parse input
|
|
for line in data:
|
|
if ':' in line:
|
|
result, constants = line.split(':')
|
|
result = int(result)
|
|
constants = [int(n) for n in constants.strip().split(' ')]
|
|
equations.append(Equation(result, constants))
|
|
|
|
# Part 1
|
|
total = 0
|
|
for equation in equations:
|
|
if equation.is_valid(None):
|
|
total += equation.result
|
|
|
|
print(f'Part 1: {total}')
|
|
|
|
|