63 lines
1.3 KiB
Python
63 lines
1.3 KiB
Python
from lib import get_data
|
|
|
|
data = get_data(__file__)
|
|
|
|
rules = {}
|
|
msgs = []
|
|
|
|
for line in data.splitlines():
|
|
if len(line.strip()) == 0:
|
|
continue
|
|
|
|
if ":" in line:
|
|
id, rule = line.split(":")
|
|
id = int(id)
|
|
|
|
branches = [[]]
|
|
for part in rule.split():
|
|
if part.startswith('"') and part.endswith('"'):
|
|
branches = part[1]
|
|
elif part == "|":
|
|
assert type(branches) is list
|
|
branches.append([])
|
|
else:
|
|
assert type(branches) is list
|
|
branches[-1].append(int(part))
|
|
rules[id] = branches
|
|
else:
|
|
msgs.append(line.strip())
|
|
|
|
|
|
def matches(xs, rule):
|
|
if xs == "" and rule == []:
|
|
return True
|
|
elif xs == "" or rule == []:
|
|
return False
|
|
|
|
current = rules[rule[0]]
|
|
if current == xs[0]:
|
|
return matches(xs[1:], rule[1:])
|
|
elif type(current) is str:
|
|
return False
|
|
elif len(current) >= 1:
|
|
for ys in current:
|
|
if matches(xs, ys + rule[1:]):
|
|
return True
|
|
return False
|
|
|
|
|
|
t = 0
|
|
for m in msgs:
|
|
if matches(m, rules[0][0]):
|
|
t += 1
|
|
print(t)
|
|
|
|
rules[8] = [[42], [42, 8]]
|
|
rules[11] = [[42, 31], [42, 11, 31]]
|
|
|
|
t = 0
|
|
for m in msgs:
|
|
if matches(m, rules[0][0]):
|
|
t += 1
|
|
print(t)
|