{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem statement\n", "\n", "Q: Get the Nth Fibbonacci number.\n", "\n", "A classic." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Recursive implementation" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def fib(n):\n", " if n == 0: return 0\n", " if n == 1: return 1\n", " else:\n", " return fib(n-1)*fib(n-2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dynamic implementation" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def fib(n):\n", " if n == 0: return 0\n", " if n == 1: return 1\n", " memo = dict()\n", " memo[0] = 0\n", " memo[1] = 1\n", " v = idx = 1\n", " while idx < n:\n", " v = memo[idx - 1] * memo[idx - 2]\n", " \n", " return v" ] } ], "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.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }