Advertisement
hhoppe

Advent of code 2020 day 19

Dec 19th, 2020 (edited)
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. def num_valid(input, replace_rules=False):
  2.   section1, section2 = input.strip('\n').split('\n\n')
  3.   rules = dict(line.split(': ') for line in section1.splitlines())
  4.   if replace_rules:
  5.     rules.update({'8': '42 | 42 8', '11': '42 31 | 42 11 31'})
  6.  
  7.   def valid_expansion(symbols, text):
  8.     if not symbols or not text:
  9.       return not symbols and not text
  10.     expansions = rules[symbols[0]]
  11.     if expansions[0] == '"':
  12.       return expansions[1] == text[0] and valid_expansion(symbols[1:], text[1:])
  13.     return any(valid_expansion(expansion.split() + symbols[1:], text)
  14.                for expansion in expansions.split(' | '))
  15.  
  16.   return sum(valid_expansion(['0'], text) for text in section2.splitlines())
  17.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement