Skip to content

Commit

Permalink
update Ch13-Recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
rambasnet committed Nov 14, 2024
1 parent ee98f95 commit 4e98b47
Showing 1 changed file with 67 additions and 16 deletions.
83 changes: 67 additions & 16 deletions notebooks/Ch13-Recursion.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -267,15 +267,15 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# Finding Fibonacci number in series\n",
"# count = 0\n",
"count = 0\n",
"def fib(n):\n",
" #global count\n",
" #count += 1\n",
" global count\n",
" count += 1\n",
" if n <= 1:\n",
" return n\n",
" f = fib(n-1) + fib(n-2)\n",
Expand All @@ -284,14 +284,22 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 9,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"fib was called 7049155 times.\n"
]
}
],
"source": [
"fib(32)\n",
"#print(count)\n",
"#assert fib(8) == 21\n",
"#assert fib(10) == 55"
"print(f'fib was called {count} times.')\n",
"assert fib(8) == 21\n",
"assert fib(10) == 55"
]
},
{
Expand All @@ -301,14 +309,38 @@
"<img src=\"./resources/recursion-fib.svg\" width=\"50%\">\n",
"\n",
"### visualize fib(4) using pythontutor.com\n",
"- https://goo.gl/YNizhH"
"- https://goo.gl/YNizhH\n",
"\n",
"### You can timeit\n",
"\n",
"- use timeit function to see how long fib(n) takes"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"from timeit import timeit"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.1521884420071729"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"timeit(\"fib(32)\", globals=globals(), number=1)"
]
Expand All @@ -325,7 +357,7 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -339,18 +371,37 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 13,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2178309\n"
]
}
],
"source": [
"print(fib_tail(32, 0, 1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 14,
"metadata": {},
"outputs": [],
"outputs": [
{
"data": {
"text/plain": [
"1.3885000953450799e-05"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"timeit(\"fib_tail(32, 0, 1)\", globals=globals(), number=1)"
]
Expand Down

0 comments on commit 4e98b47

Please sign in to comment.