Created
December 19, 2020 06:03
-
-
Save sciyoshi/8e09c29cce8516f457c7236403820080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParseError(Exception): | |
pass | |
def parse_rule(alts): | |
def parse(inp): | |
for rule in alts: | |
s = inp | |
for el in rule: | |
try: | |
s = rules[el](s) | |
except ParseError: | |
break | |
else: | |
return s | |
raise ParseError | |
return parse | |
def parse_str(st): | |
def parse(inp): | |
if inp and inp[0] == st: | |
return inp[1:] | |
else: | |
raise ParseError | |
return parse | |
rules = {} | |
teststr = [] | |
for l in open('inputs/day19.txt').read().splitlines(): | |
if l.startswith("a") or l.startswith("b"): | |
teststr.append(l) | |
continue | |
if not l.strip(): | |
break | |
n, rule = l.split(": ") | |
if rule.startswith('"'): | |
rules[int(n)] = parse_str(rule.strip('"')) | |
else: | |
alts = [] | |
for alt in rule.split(" | "): | |
alts.append(ints(alt)) | |
rules[int(n)] = parse_rule(alts) | |
def parse_modified(inp): | |
i = 0 | |
s = rules[42](inp) | |
while s: | |
s2 = s | |
try: | |
for j in range(i): | |
s2 = rules[31](s2) | |
if s2 == "": | |
return "" | |
except ParseError: | |
pass | |
s = rules[42](s) | |
i += 1 | |
raise ParseError | |
PART1 = False | |
count = 0 | |
for s in teststr: | |
try: | |
if (rules[0](s) if PART1 else parse_modified(s)) == "": | |
count += 1 | |
except ParseError: | |
pass | |
print(count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment