{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import json\n", "\n", "pi12 = json.load(open('advent12.json'))\n", "len(pi12)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def jsum(term):\n", " if isinstance(term, dict):\n", " return sum(jsum(k) + jsum(v) for k, v in term.items())\n", " elif isinstance(term, list):\n", " return sum(jsum(e) for e in term)\n", " elif isinstance(term, int):\n", " return term\n", " elif isinstance(term, str):\n", " return 0\n", " else:\n", " raise ArgumentError" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jsum({})" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "191164" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jsum(pi12)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def jsum2(term):\n", " if isinstance(term, dict):\n", " if 'red' in term or 'red' in term.values():\n", " return 0\n", " else:\n", " return sum(jsum2(k) + jsum2(v) for k, v in term.items())\n", " elif isinstance(term, list):\n", " return sum(jsum2(e) for e in term)\n", " elif isinstance(term, int):\n", " return term\n", " elif isinstance(term, str):\n", " return 0\n", " else:\n", " raise ArgumentError" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "87842" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "jsum2(pi12)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }