39 lines
867 B
Python
39 lines
867 B
Python
#!/usr/bin/env python3
|
|
|
|
lines = (x.strip() for x in open("input.txt"))
|
|
rules = {}
|
|
|
|
|
|
def yield_rule(line, rule):
|
|
if len(rule) > 0:
|
|
elem, *tail = rule
|
|
for rest in check(line, elem):
|
|
yield from yield_rule(rest, tail)
|
|
else:
|
|
yield line
|
|
|
|
|
|
def check(line, idx):
|
|
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)
|
|
|
|
|
|
sum = 0
|
|
for line in lines:
|
|
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)
|