import argparse import functools parser = argparse.ArgumentParser() parser.add_argument("ifile", type=argparse.FileType('r')) args = parser.parse_args() ILLEGAL_CHARS = { ')': '(', ']': '[', '}': '{', '>': '<' } def protoBalance(stack, char): if stack is None: return None if char not in ILLEGAL_CHARS.keys(): return stack + [char] else: prev = stack[-1] if prev != ILLEGAL_CHARS[char]: return None return stack[:-1] filelines = args.ifile.readlines() protoLines = filter(lambda line: functools.reduce(protoBalance, line, []) is not None, map(str.strip, filelines)) COMPLETION_CHARS = { '{': ('}', 3), '(': (')', 1), '[': (']', 2), '<': ('>', 4) } def protoComplete(seq: str): stack = functools.reduce(lambda stack, char: stack + [char] if char in COMPLETION_CHARS.keys() else stack[:-1], seq, []) return functools.reduce(lambda acc, val: acc * 5 + COMPLETION_CHARS[val][1], reversed(stack), 0) scores = list(map(protoComplete, protoLines)) scores.sort() print(scores[int(len(scores) / 2)])