Tweaks on 10 an 11
This commit is contained in:
109
11/11_depthfirst_recursion_w_memo.ipynb
Normal file
109
11/11_depthfirst_recursion_w_memo.ipynb
Normal file
@@ -0,0 +1,109 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#input = r'''0 1 10 99 999'''\n",
|
||||
"#input = r'''125 17'''\n",
|
||||
"input = r'''475449 2599064 213 0 2 65 5755 51149'''\n",
|
||||
"\n",
|
||||
"stones = [int(x) for x in input.split()]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from functools import lru_cache\n",
|
||||
"\n",
|
||||
"@lru_cache(maxsize=None)\n",
|
||||
"def step(stone,steps):\n",
|
||||
" if steps == 1:\n",
|
||||
" if stone == 0:\n",
|
||||
" return 1\n",
|
||||
" elif (tx_stone := str(stone)) and len(tx_stone) %2 == 0:\n",
|
||||
" return 2\n",
|
||||
" else:\n",
|
||||
" return 1\n",
|
||||
" else:\n",
|
||||
" if stone == 0:\n",
|
||||
" return step(1,steps-1)\n",
|
||||
" elif (tx_stone := str(stone)) and len(tx_stone) %2 == 0:\n",
|
||||
" half = len(tx_stone)//2\n",
|
||||
" left = int(tx_stone[:half])\n",
|
||||
" right = int(tx_stone[half:])\n",
|
||||
" x_left = step(left,steps-1)\n",
|
||||
" x_right = step(right,steps-1)\n",
|
||||
" return x_left + x_right\n",
|
||||
" else:\n",
|
||||
" return(step(stone*2024,steps-1))\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"193269"
|
||||
]
|
||||
},
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"sum([step(stone,25) for stone in stones])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 21,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"228449040027793"
|
||||
]
|
||||
},
|
||||
"execution_count": 21,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"sum([step(stone,75) for stone in stones])"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "advent",
|
||||
"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.13.0"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
Reference in New Issue
Block a user