Advertisement
Guest User

Untitled

a guest
Dec 19th, 2020
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. import regex
  2.  
  3. with open("in.txt") as f:
  4.     rule_text, match_strings = f.read().split("\n\n")
  5.  
  6. rules = {}
  7. for l in rule_text.split("\n"):
  8.     ix, rule = l.split(":")
  9.     if '"' in rule:
  10.         rules[int(ix)] = rule.strip('" \n')
  11.     else:
  12.         rules[int(ix)] = [[int(p) for p in part.strip().split(" ")] for part in rule.split("|")]
  13.  
  14.  
  15. def define_regexp(i):
  16.     if isinstance(rules[i], str):
  17.         p = rules[i]
  18.     else:  # list of lists
  19.         options = ["".join(f"(?&r{j})" for j in option) for option in rules[i]]
  20.         p = "|".join(f"(?:{r})" for r in options)
  21.     return f"(?P<r{i}>{p})"
  22.  
  23.  
  24. for part in [1, 2]:
  25.     if part == 2:
  26.         rules.update({8: [[42], [42, 8]], 11: [[42, 31], [42, 11, 31]]})
  27.     definitions = "(?(DEFINE)" + "".join(define_regexp(k) for k in rules.keys()) + ")"
  28.     pattern = regex.compile(definitions + "^(?&r0)$")
  29.     count = sum(pattern.match(s) is not None for s in match_strings.split("\n"))
  30.     print(count)
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement