Guest User

Untitled

a guest
Dec 9th, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. import numpy as np
  2. def part_1():
  3.   #keep track of what goes with what
  4.   matches = {'}':'{',']':'[',')':'(','>':'<'}
  5.   handle = open('10a.txt','r')
  6.  
  7.   sum = 0
  8.   #keep track of the scores for each symbol, 'bonus' is for part 2
  9.   score = {')':3,']':57,'}':1197,'>':25137}
  10.   bonus =  {'(':1,'[':2,'{':3,'<':4}
  11.   #track scores for each line in part 2
  12.   totals = []
  13.  
  14.   for line in handle:
  15.     bad = False #we only score lines with missing pieces, rather than invalid ones for part 2
  16.     #going to push opens onto the stack, and pop closes
  17.     #if we see a close and the top of the stack doesn't match, we're in trouble
  18.     stack = []
  19.     for x in line.strip():
  20.       if x in ['{','(','[','<']:
  21.         stack.append(x) #push opens
  22.       else:
  23.         if stack[-1] == matches[x]:
  24.           stack.pop() #pop closes
  25.         else:
  26.           #we found an illegal close, mark this line as bad and add it to the sum
  27.           bad = True
  28.           sum+=score[x]
  29.           break #if python had labeled continues, I could continue the outer loop
  30.          
  31.     #time for part 2  
  32.     if not bad:
  33.       total = 0
  34.       #just go through what's left on the stack in reverse order closing them
  35.       for x in stack[::-1]:
  36.         total *= 5
  37.         total += bonus[x]
  38.       totals.append(total)
  39.   print(sum)
  40.   print(np.median(np.array(totals))) #for some reason we take the median?2995077699
  41.  
  42. part_1()
Advertisement
Add Comment
Please, Sign In to add comment