File tree Expand file tree Collapse file tree 5 files changed +449
-0
lines changed Expand file tree Collapse file tree 5 files changed +449
-0
lines changed Original file line number Diff line number Diff line change
1
+ 1 + 2 * 3 + 4 * 5 + 6
Original file line number Diff line number Diff line change
1
+ 1 + (2 * 3) + (4 * (5 + 6))
Original file line number Diff line number Diff line change
1
+ 2 * 3 + (4 * 5)
2
+ 5 + (8 * 3 + 9 + 3 * 4 * 3)
3
+ 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
4
+ ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
Original file line number Diff line number Diff line change
1
+ import os
2
+ import sys
3
+
4
+ debug = True
5
+
6
+ fileName = ""
7
+ try :
8
+ fileName = sys .argv [1 ]
9
+ if len (fileName ) < 1 :
10
+ fileName = "18.txt"
11
+ except :
12
+ fileName = "18.txt"
13
+ if debug :
14
+ print (fileName )
15
+
16
+ def solve (lines , precedence ):
17
+ solutions = []
18
+ for line in lines :
19
+ #convert to reverse polish notation
20
+ result = ""
21
+ stack = []
22
+ for char in line :
23
+ if char .isdigit ():
24
+ result += char
25
+ if char == "(" :
26
+ stack .append (char )
27
+ if char == ")" :
28
+ while len (stack ) > 0 and stack [- 1 ] != "(" :
29
+ result += stack .pop ()
30
+ stack .pop ()
31
+ if char == "+" or char == "*" :
32
+ while len (stack ) > 0 and stack [- 1 ] != "(" and precedence [char ] <= precedence [stack [- 1 ]]:
33
+ result += stack .pop ()
34
+ stack .append (char )
35
+ while len (stack ) > 0 :
36
+ result += stack .pop ()
37
+
38
+ #evaluate reverse polish notation to an int
39
+ stack = []
40
+ for char in result :
41
+ if char .isdigit ():
42
+ stack .append (int (char ))
43
+ if char == "+" or char == "*" :
44
+ result = 0
45
+ two = stack .pop ()
46
+ one = stack .pop ()
47
+ if char == "+" :
48
+ result = int (one ) + int (two )
49
+ else :
50
+ result = int (one ) * int (two )
51
+ stack .append (result )
52
+ solutions .append (stack [0 ])
53
+ return solutions
54
+
55
+ with open (fileName ) as file :
56
+ lines = file .readlines ()
57
+
58
+ solutions = solve (lines , {"+" :1 ,"*" :1 })
59
+ if debug :
60
+ print (solutions )
61
+ total = 0
62
+ for sol in solutions :
63
+ total += sol
64
+ print ("part 1" , total ) #part 1
65
+
66
+ solutions = solve (lines , {"+" :2 ,"*" :1 })
67
+ if debug :
68
+ print (solutions )
69
+ total = 0
70
+ for sol in solutions :
71
+ total += sol
72
+ print ("part 2" , total ) #part 2
You can’t perform that action at this time.
0 commit comments