From 375f3a869ba2f0414abaab0e98b8e6af02889e9b Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 9 May 2025 19:36:51 +0100 Subject: [PATCH] 2017: d09: ex2: add solution --- 2017/d09/ex2/ex2.py | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 2017/d09/ex2/ex2.py diff --git a/2017/d09/ex2/ex2.py b/2017/d09/ex2/ex2.py new file mode 100755 index 0000000..60b5a6f --- /dev/null +++ b/2017/d09/ex2/ex2.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +import sys +from typing import NamedTuple + + +class Group(NamedTuple): + children: list["Group"] + + +def solve(input: str) -> int: + def parse_group(input: str) -> tuple[Group, str, int]: + garbage = False + cancel = False + stack: list[Group] = [] + total_garbage = 0 + for i, c in enumerate(input): + if cancel: + assert garbage # Sanity check + cancel = False + continue + if garbage: + if c == "!": + cancel = True + elif c == ">": + garbage = False + else: + total_garbage += 1 + continue + if c == "<": + garbage = True + continue + if c == "{": + stack.append(Group([])) + continue + if c == "}": + top = stack.pop() + if stack: + stack[-1].children.append(top) + continue + return top, input[i + 1 :], total_garbage + assert False # Sanity check + + def parse(input: str) -> tuple[Group, int]: + groups, input, total_garbage = parse_group(input) + assert not input # Sanity check + return groups, total_garbage + + _, total_garbage = parse(input.strip()) + return total_garbage + + +def main() -> None: + input = sys.stdin.read() + print(solve(input)) + + +if __name__ == "__main__": + main()