# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Day 12: JSAbacusFramework.io
# Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.
#
# They have a JSON document which contains a variety of things: arrays (`[1,2,3]`), objects (`{"a":1, "b":2}`), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.
#
# For example:
#
# * `[1,2,3]` and `{"a":2,"b":4}` both have a sum of 6.
# * `[[[3]]]` and `{"a":{"b":4},"c":-1}` both have a sum of 3.
# * `{"a":[-1,1]}` and `[-1,{"a":1}]` both have a sum of 0.
# * `[]` and `{}` both have a sum of 0.
# You will not encounter any strings containing numbers.
#
# What is the sum of all numbers in the document?
#
#

import json
with open("input.txt","r") as f:
    input_data = json.load(f)


def all_number(input_data):
    if isinstance(input_data, int):
        return input_data
    
    if isinstance(input_data, str):
        return 0
    
    if isinstance(input_data, list):
        return sum([all_number(x) for x in input_data])
    
    if isinstance(input_data, dict):
        return sum([all_number(x) for x in input_data.values()])


all_number(input_data)


# # Part Two
# Uh oh - the Accounting-Elves have realized that they double-counted everything red.
#
# Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects ({...}), not arrays ([...]).
#
# * `[1,2,3]` still has a sum of 6.
# * `[1,{"c":"red","b":2},3]` now has a sum of 4, because the middle object is ignored.
# * `{"d":"red","e":[1,2,3,4],"f":5}` now has a sum of 0, because the entire structure is ignored.
# * `[1,"red",5]` has a sum of 6, because "red" in an array has no effect.

def all_number_2(input_data):
    if isinstance(input_data, int):
        return input_data
    
    if isinstance(input_data, str):
        return 0
    
    if isinstance(input_data, list):
        return sum([all_number_2(x) for x in input_data])
    
    if isinstance(input_data, dict):
        children = input_data.values()
        if "red" in children:
            return 0
        return sum([all_number_2(x) for x in children])


all_number_2(input_data)



StarcoderdataJupyterScriptsDedupFiltered