]> git.sommitrealweird.co.uk Git - advent-of-code-2020.git/blob - day18/badmath.py
b7e6ddab1c2c7c7dd2f5d95537ab041a513259ff
[advent-of-code-2020.git] / day18 / badmath.py
1 #!/usr/bin/python3
2
3 import sys
4
5 filename="p1_71.txt"
6 if len(sys.argv) > 1:
7     filename=sys.argv[1]
8
9 def parse_sum(oursum):
10     parts = oursum.split()
11     new_parts=[]
12     for part in parts:
13         if part[0]=="(":
14             for index,c in enumerate(part):
15                 if c=="(":
16                     new_parts.append("(")
17                 else:
18                     new_parts.append(part[index:])
19                     break
20         elif part[-1]==")":
21             got_number=False
22             for index,c in enumerate(part):
23                 if c==")":
24                     if not got_number:
25                         new_parts.append(part[0:index])
26                         got_number=True
27                     new_parts.append(c)
28         else:
29             new_parts.append(part)
30     return new_parts
31
32 def do_sum(parts):
33     cur_total=0
34     next_oper="+"
35     bracketed=[]
36     in_brackets=0
37     for part in parts:
38         if in_brackets > 0 and part != ")" and part != "(":
39             bracketed.append(part)
40             continue
41         if in_brackets > 0 and part == ")":
42             in_brackets-=1
43             bracketed.append(part)
44             if in_brackets == 0:
45                 part=do_sum(bracketed[1:-1])
46                 bracketed.clear()
47             else:
48                 continue
49         if part == "+":
50             next_oper="+"
51         elif part == "*":
52             next_oper="*"
53         elif part == "(":
54             in_brackets+=1
55             bracketed.append(part)
56         else:
57             part=int(part)
58             if next_oper == "+":
59                 cur_total+=part
60             else:
61                 cur_total*=part
62     return cur_total
63
64 total=0
65 total2=0
66 for line in [line.rstrip() for line in open(filename, "r")]:
67     answer=do_sum(parse_sum(line))
68     total+=answer
69
70 print("Part 1 Total:", total)
71
72