Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def part_1():
- #keep track of what goes with what
- matches = {'}':'{',']':'[',')':'(','>':'<'}
- handle = open('10a.txt','r')
- sum = 0
- #keep track of the scores for each symbol, 'bonus' is for part 2
- score = {')':3,']':57,'}':1197,'>':25137}
- bonus = {'(':1,'[':2,'{':3,'<':4}
- #track scores for each line in part 2
- totals = []
- for line in handle:
- bad = False #we only score lines with missing pieces, rather than invalid ones for part 2
- #going to push opens onto the stack, and pop closes
- #if we see a close and the top of the stack doesn't match, we're in trouble
- stack = []
- for x in line.strip():
- if x in ['{','(','[','<']:
- stack.append(x) #push opens
- else:
- if stack[-1] == matches[x]:
- stack.pop() #pop closes
- else:
- #we found an illegal close, mark this line as bad and add it to the sum
- bad = True
- sum+=score[x]
- break #if python had labeled continues, I could continue the outer loop
- #time for part 2
- if not bad:
- total = 0
- #just go through what's left on the stack in reverse order closing them
- for x in stack[::-1]:
- total *= 5
- total += bonus[x]
- totals.append(total)
- print(sum)
- print(np.median(np.array(totals))) #for some reason we take the median?2995077699
- part_1()
Advertisement
Add Comment
Please, Sign In to add comment