b.py (1019B) [raw]
1 #!/usr/bin/env python3 2 import sys 3 from collections import defaultdict 4 5 match = { 6 "}": "{", 7 ")": "(", 8 ">": "<", 9 "]": "[", 10 } 11 12 rmatch = { 13 "{": "}", 14 "(": ")", 15 "<": ">", 16 "[": "]", 17 } 18 19 pts = { 20 ")": 1, 21 "]": 2, 22 "}": 3, 23 ">": 4, 24 } 25 26 27 def score(seq): 28 score = 0 29 for c in seq: 30 score *= 5 31 score += pts[c] 32 return score 33 34 35 scores = [] 36 for l in sys.stdin: 37 mem = [] 38 corrupt = False 39 for c in l.strip(): 40 if c in ["{", "(", "<", "["]: 41 mem.append(c) 42 elif c in ["}", ")", ">", "]"]: 43 m = match[c] 44 if mem.pop() != m: 45 # this is an corrupt line, skip it! 46 corrupt = True 47 break 48 else: 49 raise Exception(f"Bad char: {c}") 50 51 # Figure out and score the remaining chars! 52 if not corrupt: 53 mem.reverse() 54 remaining = [rmatch[c] for c in mem] 55 scores.append(score(remaining)) 56 57 ss = sorted(scores) 58 print(ss[int(len(ss) / 2)])