Skip to content

Commit 757c74d

Browse files
committed
recursive tree
1 parent 80ed9b6 commit 757c74d

File tree

1 file changed

+57
-3
lines changed

1 file changed

+57
-3
lines changed

2018/Playground.ipynb

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"cells": [
33
{
44
"cell_type": "code",
5-
"execution_count": 55,
5+
"execution_count": 117,
66
"metadata": {},
77
"outputs": [],
88
"source": [
@@ -15,7 +15,7 @@
1515
},
1616
{
1717
"cell_type": "code",
18-
"execution_count": 52,
18+
"execution_count": 101,
1919
"metadata": {},
2020
"outputs": [],
2121
"source": [
@@ -24,7 +24,7 @@
2424
},
2525
{
2626
"cell_type": "code",
27-
"execution_count": 78,
27+
"execution_count": 125,
2828
"metadata": {
2929
"scrolled": false
3030
},
@@ -58,6 +58,60 @@
5858
" print(f\"Part {p}:\", recur(map(int, data.split()), part=p)[1])"
5959
]
6060
},
61+
{
62+
"cell_type": "code",
63+
"execution_count": 126,
64+
"metadata": {},
65+
"outputs": [
66+
{
67+
"name": "stdout",
68+
"output_type": "stream",
69+
"text": [
70+
"Part 1: 36566\n",
71+
"Part 2: 30548\n"
72+
]
73+
}
74+
],
75+
"source": [
76+
"# Approach 2\n",
77+
"# \n",
78+
"# Recursively build tree first\n",
79+
"\n",
80+
"from dataclasses import dataclass\n",
81+
"from typing import List, Union\n",
82+
"\n",
83+
"@dataclass\n",
84+
"class node:\n",
85+
" meta: int = 0\n",
86+
" children: List['node'] = ()\n",
87+
" \n",
88+
" def part_1(self) -> int:\n",
89+
" return sum(self.meta) + sum(n.part_1() for n in self.children)\n",
90+
"\n",
91+
" def part_2(self) -> int:\n",
92+
" if self.children:\n",
93+
" return sum(self.children[m-1].part_2() \n",
94+
" for m in self.meta if 0 < m <= len(self.children))\n",
95+
" else:\n",
96+
" return sum(self.meta)\n",
97+
"\n",
98+
" \n",
99+
"def recur_tree(N): \n",
100+
" n_children, n_meta, *N = N\n",
101+
" \n",
102+
" children = []\n",
103+
" for _ in range(n_children):\n",
104+
" N, child = recur_tree(N)\n",
105+
" children += [child]\n",
106+
"\n",
107+
" return N[n_meta:], node(meta=N[:n_meta], children=children)\n",
108+
" \n",
109+
"tree = recur_tree(map(int, data.split()))[1]\n",
110+
"\n",
111+
"print(f\"Part 1:\", tree.part_1())\n",
112+
"print(f\"Part 2:\", tree.part_2())"
113+
]
114+
},
61115
{
62116
"cell_type": "code",
63117
"execution_count": null,

0 commit comments

Comments
 (0)