-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpart_one.py
63 lines (44 loc) · 1.64 KB
/
part_one.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from itertools import product
from typing import override
from infrastructure.solutions.base import Solution
Equation = tuple[int, list[int]]
OPERATIONS = {
'+': lambda x, y: x + y,
'*': lambda x, y: x * y,
}
class Year2024Day7Part1Solution(Solution):
@classmethod
@override
def parse_input(cls, text_input: str) -> dict[str, list[Equation]]:
equations = []
for line in text_input.split('\n'):
answer, expression = line.split(': ')
answer = int(answer)
expression = [int(num) for num in expression.split()]
equations.append((answer, expression))
return {'equations': equations}
@classmethod
@override
def solve(cls, equations: list[Equation]) -> int:
"""
Time: O(n*k^m)
Space: O(1)
Where n - number of equations,
m - maximum size of equation
k - number of possible operations
"""
possible_sum = 0
for answer, expression in equations:
for operations in product(OPERATIONS.keys(), repeat=len(expression) - 1):
possible_answer = expression[0]
for i, operation in enumerate(operations, start=1):
possible_answer = OPERATIONS[operation](possible_answer, expression[i])
# Early break for exceeded value
if possible_answer > answer:
break
if possible_answer == answer:
possible_sum += answer
break
return possible_sum
if __name__ == '__main__':
print(Year2024Day7Part1Solution.main())