Skip to content

Commit

Permalink
[chore] replace py file with notebook
Browse files Browse the repository at this point in the history
  • Loading branch information
gitgik committed Feb 25, 2021
1 parent 36a446f commit 09711dd
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 43 deletions.
97 changes: 97 additions & 0 deletions recursion/fibonacci.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
{
"metadata": {
"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.9.0-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python3",
"display_name": "Python 3.9.0 64-bit",
"metadata": {
"interpreter": {
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
}
}
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def fibonacci(n, memoize={1:0, 2: 1}):\n",
" \"\"\"\n",
" Nth fibonacci number using memoization.\n",
" \n",
" O(n) space and time\n",
" \"\"\"\n",
" if n < 0:\n",
" raise TypeError('Value of n must be a positive integer')\n",
" if n in memoize:\n",
" return memoize[n]\n",
" else:\n",
" memoize[n] = fibonacci(n - 1, memoize) + fibonacci(n - 2, memoize)\n",
" return memoize[n]\n",
"\n",
"\n",
"def efficient_fibonacci(n):\n",
" \"\"\"\n",
" nth fibonacci number iteratively.\n",
"\n",
" Complexity:\n",
" O(n) time,\n",
" O(1) space, since we are only storing two array values at any given time.\n",
" \"\"\"\n",
" last_two = [0, 1]\n",
"\n",
" counter = 3\n",
" while counter <= n:\n",
" next_fibonacci = sum(last_two)\n",
" last_two = [last_two[1], next_fibonacci]\n",
" counter += 1\n",
" # the else clause caters for the edge case of the first fibo number == 0\n",
" return last_two[1] if n > 1 else last_two[0]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"89"
]
},
"metadata": {},
"execution_count": 3
}
],
"source": [
"efficient_fibonacci(12)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}
43 changes: 0 additions & 43 deletions recursion/fibonacci.py

This file was deleted.

0 comments on commit 09711dd

Please sign in to comment.