File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+ import math
3+
4+ with open ("input" ) as f :
5+ inp = f .read ().strip ().split ("\n " )
6+
7+
8+ def calculate (nums , op ):
9+ if op == "+" :
10+ return sum (nums )
11+ elif op == "*" :
12+ return math .prod (nums )
13+
14+
15+ # Part 1
16+ operators = inp [- 1 ].split ()
17+ numbers = defaultdict (list )
18+ for line in inp [:- 1 ]:
19+ for i , x in enumerate (line .split ()):
20+ numbers [i ].append (int (x ))
21+
22+ print (sum (calculate (nums , op ) for nums , op in zip (numbers .values (), operators )))
23+
24+
25+ # Part 2
26+ grid = {x + y * 1j : c for y , line in enumerate (inp [:- 1 ]) for x , c in enumerate (line )}
27+ R = len (inp ) - 1
28+ C = len (inp [0 ])
29+
30+ numbers = defaultdict (list )
31+ c = 0
32+ for x in range (C ):
33+ n = "" .join (grid [x + y * 1j ] for y in range (R )).strip ()
34+ if not n .isdigit ():
35+ c += 1
36+ else :
37+ numbers [c ].append (int (n ))
38+
39+ print (sum (calculate (nums , op ) for nums , op in zip (numbers .values (), operators )))
You can’t perform that action at this time.
0 commit comments