Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from copy import deepcopy
- CLOSE_CHARS = '}]>)'
- def read_and_init(fn):
- with open(fn, 'r') as f:
- return f.read().splitlines()
- def scan(chunk) -> int:
- depth = []
- mates = {'}': '{', ']': '[', '>': '<', ')': '('}
- scoring = {')': 3, ']': 57, '}': 1197, '>': 25137}
- p = 0
- while p < len(chunk):
- if chunk[p] in CLOSE_CHARS:
- if depth[-1] != mates[chunk[p]]:
- return scoring[chunk[p]]
- else:
- depth.pop()
- else:
- depth.append(chunk[p])
- p += 1
- return 0
- def autocomplete(chunks):
- scores = []
- mates = {'(': ')', '[': ']', '{': '}', '<': '>'}
- scoring = {')': 1, ']': 2, '}': 3, '>': 4}
- for chunk in chunks:
- p = 0
- score = 0
- depth = []
- while p < len(chunk):
- if chunk[p] in CLOSE_CHARS:
- depth.pop()
- else:
- depth.append(chunk[p])
- p += 1
- depth = list(reversed([mates[d] for d in depth]))
- for char in depth:
- score = score * 5 + scoring[char]
- scores.append(score)
- scores.sort()
- return scores[len(scores) // 2]
- def part1(chunks: list):
- score = 0
- for chunk in chunks:
- score += scan(chunk)
- return score
- def part2(chunks: list):
- chunks_copy = deepcopy(chunks)
- p = 0
- while p < len(chunks):
- if scan(chunks[p]) > 0:
- chunks_copy.remove(chunks[p])
- p += 1
- score = autocomplete(chunks_copy[:])
- return score
- c = read_and_init(os.path.dirname(__file__) + '\\in.txt')
- res1 = part1(c)
- print('Part 1:', res1)
- res2 = part2(c)
- print('Part 2:', res2)
Advertisement
Add Comment
Please, Sign In to add comment