b.py (2367B) [raw]
1 #!/usr/bin/env python3 2 import sys 3 4 5 # Map abcdefg -> 1234567 (orig positions) 6 def mapit(preface): 7 M = {} 8 9 def mset(sig, val): 10 if val in M: 11 print(val) 12 print(M) 13 raise Exception("val already in M!") 14 else: 15 M[val] = set(sig) 16 17 todo = preface[:] 18 while todo: 19 sig = todo.pop(0) 20 if len(sig) == 2: 21 mset(sig, "1") 22 continue 23 elif len(sig) == 3: 24 mset(sig, "7") 25 continue 26 elif len(sig) == 4: 27 mset(sig, "4") 28 continue 29 elif len(sig) == 7: 30 mset(sig, "8") 31 continue 32 elif len(sig) == 6: 33 # either 0/6/9 34 if contains(sig, M, "4"): 35 mset(sig, "9") 36 continue 37 elif "4" in M and contains(sig, M, "7"): 38 mset(sig, "0") 39 continue 40 elif "4" in M and "7" in M: 41 mset(sig, "6") 42 continue 43 elif len(sig) == 5: 44 # either 2/3/5 45 if contains(sig, M, "1"): 46 mset(sig, "3") 47 continue 48 if "1" in M and ("6" in M or "9" in M): 49 if contained(sig, M, "6") or contained(sig, M, "9"): 50 mset(sig, "5") 51 continue 52 else: 53 mset(sig, "2") 54 continue 55 56 # unfound, retry 57 todo.append(sig) 58 59 return M 60 61 62 def contains(sig, M, query): 63 if query not in M: 64 return False 65 66 for c in M[query]: 67 if c not in sig: 68 return False 69 return True 70 71 72 def contained(sig, M, query): 73 if query not in M: 74 return False 75 76 for c in sig: 77 if c not in M[query]: 78 return False 79 return True 80 81 82 total = 0 83 for l in sys.stdin: 84 # Sort into two buckets per line 85 seen = False 86 preface = [] 87 output = [] 88 for sig in l.strip().split(" "): 89 if sig == "|": 90 seen = True 91 continue 92 if seen: 93 output.append(sig) 94 else: 95 preface.append(sig) 96 97 # Now get a mapping... 98 M = mapit(preface) 99 100 out = "" 101 for o in output: 102 s = set(o) 103 for m, v in M.items(): 104 if s == v: 105 out += m 106 total += int(out) 107 108 print(total)