import fileinput scores = [ 3, 57, 1197, 25137 ] opening_chars = ['(', '[', '{', '<'] closing_chars = [')', ']', '}', '>'] lines = fileinput.input() score = [] completions = [] completion_points = [] for line in lines: total = 0 stack = [] line = line.strip() complete = True for column, c in enumerate(line): if c in opening_chars: stack.append(c) if c in closing_chars: i = closing_chars.index(c) if stack[-1] != opening_chars[i]: expected_i = opening_chars.index(stack[-1]) # print(line) # print(''.join(column*[' ']+['^'])) # print(f'Expected {closing_chars[expected_i]} but found {c}') # print('') score.append(scores[i]) complete = False break stack.pop() if not complete: continue # the line is just incomplete completion = [] while len(stack) > 0: i = opening_chars.index(stack.pop()) char = closing_chars[i] total = total*5 + (i+1) completion.append(char) completion_points.append(total) print(''.join(completion)) completion_points.sort() print('part 1') print(score) print(sum(score)) print('part 2') print(completion_points) print(completion_points[len(completion_points)//2])