-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
63 lines (45 loc) · 1.6 KB
/
main.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
# Import common core
import sys
sys.path.append('../common_core')
from common_core import ft_core
# Import requirements
import re
input_file = sys.argv[1]
class Nbr(int):
'''
Class for storing numbers from math expressions.
The subtraction method will perform a multiplication instead, in order to
perform multiplications with same precedence as additions (Part One).
The multiplication method will perform an addition instead, in order to
perform additions with more precedence than multiplications.
'''
def __add__(self, x):
return Nbr(int(self) + x)
def __sub__(self, x):
return Nbr(int(self) * x)
def __mul__(self, x):
return Nbr(int(self) + x)
def ft_input_parser(raw_input):
return raw_input
def ft_eval_expr(data, part):
'''
This function applies regex to each line (string) of the input, convertingr
digits to Nbr objects, thus replacing '*' with '-' (in order to perform
multiplications with same precedence as additions), and (for Part Two)
'+' with '*' (in order to perform additions with more precedence than
multiplications), thus applying eval() to the resulting expression.
It returns the sum of all eval() results (for each line in the input).
'''
def regex(line):
if part == 1:
return re.sub(r'(\d+)', r'Nbr(\1)', line).replace('*', '-')
if part == 2:
return re.sub(r'(\d+)', r'Nbr(\1)', line\
).replace('*', '-').replace('+', '*')
return sum(eval(regex(line)) for line in data)
def ft_part1(data):
return ft_eval_expr(data, 1)
def ft_part2(data):
return ft_eval_expr(data, 2)
if __name__ == '__main__':
ft_core(input_file, ft_input_parser, ft_part1, ft_part2)