43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
#!/usr/bin/env python3
|
|
import re
|
|
|
|
lines = (x.strip() for x in open("input.txt"))
|
|
rules = {}
|
|
|
|
|
|
def yield_rule(line, rule, depth):
|
|
if len(rule) > 0:
|
|
elem, *tail = rule
|
|
for rest in check(line, elem, depth+1):
|
|
yield from yield_rule(rest, tail, depth)
|
|
else:
|
|
yield line
|
|
|
|
|
|
def check(line, idx, depth=0):
|
|
if depth <= 100:
|
|
rs = rules[idx]
|
|
if isinstance(rs, str):
|
|
if line.startswith(rs):
|
|
yield line[len(rs):]
|
|
else:
|
|
for rule in rules[idx]:
|
|
yield from yield_rule(line, rule, depth)
|
|
|
|
|
|
sum = 0
|
|
for line in lines:
|
|
line = '11: 42 31 | 42 11 31' if line.startswith('11: ') else line
|
|
line = '8: 42 | 42 8' if line.startswith('8:') else line
|
|
if ":" in line:
|
|
idx, r = line.split(": ")
|
|
idx = int(idx)
|
|
r = r[1:len(r)-1] if r.startswith('"') else [[int(num) for num in x.split()] for x in r.split(" | ")]
|
|
rules[idx] = r
|
|
elif line != "":
|
|
for rest in check(line, 0):
|
|
if rest == "":
|
|
sum += 1
|
|
print(sum)
|
|
exit(0)
|