openers = ['(', '[', '{', '<'] closers = [')', ']', '}', '>'] points = [3, 57, 1197, 25137] scores = [] with open('data', 'r') as fp: # NOTE(dev): We assume all lines are the same length for line in fp: stack = [] corrupt = False for ch in line.strip(): if(ch in openers): stack.append(ch) else: try: i = closers.index(ch) last = stack[-1] stack.pop() if(last != openers[i]): corrupt = True break except ValueError: # not an opener or closer! pass if(not corrupt and len(stack)): line_score = 0 for ch in reversed(stack): line_score *= 5 line_score += openers.index(ch) + 1 scores.append(line_score) scores.sort() print('scores[int(', len(scores), '/ 2 )]') print(scores[int(len(scores) / 2)])