2.py (1141B) [raw]
1 #!/usr/bin/env python3 2 import sys 3 from collections import defaultdict 4 5 G = [] 6 for l in sys.stdin: 7 chars = [c for c in l.strip()] 8 G.append(chars) 9 10 def safeget(i, j): 11 if i > 0 and j > 0 and i < len(G) and j < len(G[0]): 12 return G[i][j] 13 return None 14 15 def getgear(i, j): 16 locs = [ 17 (i-1,j-1), 18 (i-1,j), 19 (i-1,j+1), 20 (i,j-1), 21 (i,j), 22 (i,j+1), 23 (i+1,j-1), 24 (i+1,j), 25 (i+1,j+1), 26 ] 27 for loc in locs: 28 if safeget(loc[0], loc[1]) == '*': 29 return loc 30 return None 31 32 gearnums = defaultdict(list) 33 for i in range(len(G)): 34 numstr = '' 35 sym = None 36 for j in range(len(G[0])): 37 if G[i][j].isdigit(): 38 numstr += G[i][j] 39 if not sym: 40 sym = getgear(i, j) 41 else: 42 if numstr and sym: 43 gearnums[sym].append(int(numstr)) 44 numstr = '' 45 sym = None 46 if numstr and sym: 47 gearnums[sym].append(int(numstr)) 48 49 tot = 0 50 for gear in gearnums: 51 if len(gearnums[gear]) == 2: 52 tot += gearnums[gear][0] * gearnums[gear][1] 53 print(tot)