From 3c69c64c18babb232b804a72ad72a3b6c5d6c8ad Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 21 May 2025 03:38:37 +0100 Subject: [PATCH] 2015: d12: ex2: add solution --- 2015/d12/ex2/ex2.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 2015/d12/ex2/ex2.py diff --git a/2015/d12/ex2/ex2.py b/2015/d12/ex2/ex2.py new file mode 100755 index 0000000..5f25859 --- /dev/null +++ b/2015/d12/ex2/ex2.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import json +import sys +from collections.abc import Iterator + +JSONValue = int | str | list["JSONValue"] | dict[str, "JSONValue"] + + +def solve(input: str) -> int: + def parse(input: str) -> JSONValue: + return json.loads(input) + + def all_numbers(doc: JSONValue) -> Iterator[int]: + if isinstance(doc, int): + yield doc + elif isinstance(doc, list): + for it in doc: + yield from all_numbers(it) + elif isinstance(doc, dict): + if "red" in doc.values(): + return + for it in doc.values(): + yield from all_numbers(it) + + doc = parse(input) + return sum(all_numbers(doc)) + + +def main() -> None: + input = sys.stdin.read() + print(solve(input)) + + +if __name__ == "__main__": + main()