Skip to content
advent of code 2015

day 12

jsabacusframework.io

approach

the document is parsed with json.loads and walked recursively by type: lists and dicts recurse, strings count as zero, anything else is a number.

part 1 is the plain sum. for part 2 the recursion returns a pair, the sum and whether the value itself is the string "red". a dict that sees that flag on any of its values returns zero; lists add up their items and never pass the flag on.

the trick

return (sum, is_red) from the recursion so the parent dict decides whether to throw the sum away.

python
def dfs2(o):
    if type(o) == list:
        s = 0
        for oo in o:
            ss, _ = dfs2(oo)
            s += ss
        return s, False
    elif type(o) == dict:
        s, r = 0, False
        for oo in o.values():
            ss, hr = dfs2(oo)
            s += ss
            r = r or hr
        return 0 if r else s, False
    elif type(o) == str:
        return 0, o == "red"
    else:
        return o, False