2024-12-07 00:52:33 -06:00

112 lines
3.1 KiB
Python

import re
with open('test.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
op = lambda x,y: x + y
for token in tokens:
if not r and token.isnumeric():
r = int(token)
elif token == '+':
op = lambda x,y: x + y
elif token == '*':
op = lambda x,y: x * y
else:
r = op(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)
def is_valid2(self, s: str | None) -> bool:
if s == None:
s = ''
for c in self.constants:
s += (str(c) + ' ')
return self.is_valid2(s[:-1])
elif ' ' in s:
s1 = s.replace(' ', '+', 1)
s2 = s.replace(' ', '*', 1)
# We do the || operator right here
if s.count(' ') >= 1:
tokens: list[str] = re.findall('\d+|\+|\*| ', s)
space_i = tokens.index(' ')
new_num = tokens[space_i - 1].strip() + tokens[space_i + 1].strip()
new_tokens = tokens[:space_i - 1]
new_i = len(new_tokens)
new_tokens.append(new_num)
new_tokens.extend(tokens[space_i + 2:])
s3 = ''
print(new_tokens)
for i, token in enumerate(new_tokens):
if token == ' ':
continue
if i > new_i - 1:
s3 += (token + ' ')
else:
s3 += token
print(s)
print(s3)
# exit()
return self.is_valid2(s1) or self.is_valid2(s2) or self.is_valid2(s3[:-1])
else:
return self.is_valid2(s1) or self.is_valid2(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}')
# Part 2
total = 0
for equation in equations:
if equation.is_valid2(None):
total += equation.result
print(f'Part 2: {total}')