Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def day19_part2(s):
- s_rules, _ = s.split('\n\n')
- rules = {'R': []}
- for line in s_rules.splitlines():
- name, s_rules = line[:-1].split('{')
- rules[name] = s_rules.split(',')
- total = 0
- initial_intervals = {category: (1, 4001) for category in 'xmas'} # (start, stop).
- stack = [('in', initial_intervals)]
- while stack:
- name, intervals = stack.pop()
- if name == 'A':
- total += math.prod(stop - start for start, stop in intervals.values())
- continue
- for rule in rules[name]:
- if rule.isalpha():
- stack.append((rule, intervals))
- break
- category, op, s_num, label = re.match(r'^(\w)([<>])(\d+):(\w+)$', rule).groups()
- num = int(s_num)
- start, stop = intervals[category]
- if op == '<':
- if start < num:
- stack.append((label, intervals | {category: (start, min(stop, num))}))
- start = max(start, num)
- else:
- if stop > num + 1:
- stack.append((label, intervals | {category: (max(start, num + 1), stop)}))
- stop = min(stop, num + 1)
- if start < stop:
- intervals[category] = start, stop
- else:
- break
- return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement