From a0d227c53e3360ec556557a1126478dbce8c861b Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 21 May 2025 03:38:29 +0100 Subject: [PATCH] 2015: d12: ex1: add solution --- 2015/d12/ex1/ex1.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 2015/d12/ex1/ex1.py diff --git a/2015/d12/ex1/ex1.py b/2015/d12/ex1/ex1.py new file mode 100755 index 0000000..c622db9 --- /dev/null +++ b/2015/d12/ex1/ex1.py @@ -0,0 +1,34 @@ +#!/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): + 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()