68 lines
1.6 KiB
Python
68 lines
1.6 KiB
Python
def read_file():
|
|
with open("input.txt","r") as f:
|
|
rules, messages = f.read().split('\n\n')
|
|
messages = messages.split('\n')
|
|
rules = rules.split('\n')
|
|
rules = {
|
|
int(r.split(':')[0]):
|
|
[[int(x) for x in sr.split()]
|
|
for sr in r.split(':')[1].split('|')]
|
|
if '"' not in r else r[-2] # a or b
|
|
for r in rules
|
|
}
|
|
return rules, messages
|
|
|
|
def consume(message, rule, rules):
|
|
if type(rules[rule]) == str:
|
|
if message and message[0] == rules[rule]:
|
|
return [message[1:]]
|
|
else:
|
|
to_be_consumed = []
|
|
for group in rules[rule]:
|
|
message_list = [message]
|
|
for rule in group:
|
|
message_list2 = []
|
|
for submessage in message_list:
|
|
message_list2 += consume(submessage, rule, rules)
|
|
message_list = message_list2
|
|
if not message_list:
|
|
break
|
|
if message_list:
|
|
to_be_consumed += message_list
|
|
return to_be_consumed
|
|
return []
|
|
|
|
"""
|
|
import re
|
|
def part1(rules,messages):
|
|
rule = rules["0"]
|
|
groups = re.findall(r'(\d)', rule)
|
|
groups = [rules[key] for key in groups]
|
|
while True:
|
|
for i in range(len(groups)):
|
|
m = re.findall(r'(\d)', groups[i])
|
|
for g in m:
|
|
groups[i] = groups[i].replace(g, rules[g])
|
|
print(groups)
|
|
test = re.findall(r'(\d)',groups[1])
|
|
if not test:
|
|
break
|
|
|
|
|
|
|
|
def part2(rules,messages):
|
|
pass
|
|
"""
|
|
|
|
def main():
|
|
rules, messages = read_file()
|
|
print(sum('' in consume(m, 0, rules) for m in messages))
|
|
|
|
rules[8] = [[42], [42, 8]]
|
|
rules[11] = [[42, 31], [42, 11, 31]]
|
|
|
|
print(sum('' in consume(m, 0, rules) for m in messages))
|
|
#print(part1(rules,messages), part2(rules,messages))
|
|
|
|
if __name__ == "__main__":
|
|
main() |