From a35861c5a8288b3948ebe2c81fa9ec45d0009894 Mon Sep 17 00:00:00 2001 From: Ben Charlton Date: Tue, 22 Dec 2020 23:22:53 +0000 Subject: [PATCH] day 19 --- 19/19.py | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 19/19.py diff --git a/19/19.py b/19/19.py new file mode 100644 index 0000000..cd6e69d --- /dev/null +++ b/19/19.py @@ -0,0 +1,93 @@ +#!/usr/bin/python3 + +import sys, re + +def is_integer(n): + try: + float(n) + except ValueError: + return False + else: + return float(n).is_integer() + +def process_rules(rules, id): + rule = rules[id] + check = rule.split(" ") + r = "(" + p = "" + q = "" + for c in check: + if is_integer(c): + r += process_rules(rules, c) + elif c == '"a"': + r += "a" + elif c == '"b"': + r += "b" + elif c == '|': + r += "|" + r += p + r += ")" + r += q + + return r + +def process_rules2(rules, id): + rule = rules[id] + check = rule.split(" ") + r = "(" + p = "" + q = "" + for c in check: + if is_integer(c): + if id == "8": + return "(" + process_rules2(rules, "42" ) + ")+" + elif id == "11": + x = [] + for t in range(1,15): + x.append("(" + process_rules2(rules, "42" )+"{" + str(t) + "}" + process_rules(rules, "31" ) + "{" + str(t) + "}"+ ")") + + return "(" + "|".join(x) + ")" + else: + r += process_rules2(rules, c) + elif c == '"a"': + r += "a" + elif c == '"b"': + r += "b" + elif c == '|': + r += "|" + r += p + r += ")" + r += q + + return r + + +rules = {} +r = r2 = "" +count = count2 = 0 +for line in sys.stdin: + line = line.rstrip() + + m = re.match(r'^(\d+): (.*?)$', line) + if m is not None: + id = m.group(1) + rule = m.group(2) + rules[id] = rule + continue + + if line == "": + r = "^" + process_rules(rules, "0") + "$" + r2 = "^" + process_rules2(rules, "0") + "$" + + m = re.match(r'^([ab]+)$', line) + if m is not None: + check = re.match(r, m.group(1)) + if check is not None: + count += 1 + + check2 = re.match(r2, m.group(1)) + if check2 is not None: + count2 += 1 + +print(1, count) +print(2, count2) \ No newline at end of file