Skip to content

Instantly share code, notes, and snippets.

@kung-foo
Last active December 19, 2020 20:03
Show Gist options
  • Save kung-foo/526a9ff4a1eee8514af243233daf01f3 to your computer and use it in GitHub Desktop.
Save kung-foo/526a9ff4a1eee8514af243233daf01f3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import re
import sys
# sys.setrecursionlimit(10000)
src = open("input.txt", "r").readlines()
src = [r.strip() for r in src if r.strip()]
rules = {}
messages = []
for line in src:
if line[0].isdigit():
t = line.split(": ")
n = int(t[0])
if n == 8:
t[1] = "42 | 42 8"
if n == 11:
t[1] = "42 31 | 42 11 31"
r = t[1].replace('"', "")
if r.isalpha():
rules[n] = r
else:
rules[n] = []
for rst in r.split(" | "):
rules[n].append([int(x) for x in rst.split(" ")])
else:
messages.append(line)
def build(n, d):
if d > 6:
if n == 8:
return "(please)"
if n == 11:
return "(stahp)"
r = rules[n]
if isinstance(r, str):
return r
p = []
for rs in r:
cs = ""
for i in rs:
cs += build(i, d + 1)
p.append(cs)
return "({})".format("|".join(p))
rxs = "^" + build(0, 0) + "$"
rx = re.compile(rxs)
c = 0
for m in messages:
if rx.match(m):
c += 1
print(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment