diff --git a/Functional_Programming/Functional_Programming.ipynb b/Functional_Programming/Functional_Programming.ipynb index cbd86aee..9b0495a2 100644 --- a/Functional_Programming/Functional_Programming.ipynb +++ b/Functional_Programming/Functional_Programming.ipynb @@ -1233,6 +1233,72 @@ } ] }, + { + "cell_type": "markdown", + "metadata": { + "id": "3RXw2BcA21La" + }, + "source": [ + "> The lru_cache decorator\n", + "\n", + "Another useful usage of a decorator is caching.\n", + "In python, the **lru_cache** remember the value from previous calls.\n", + "\n", + "Using a cache in a function that calculate the same value multiple time reduce drastically the amount of computation involved : " + ] + }, + { + "cell_type": "code", + "metadata": { + "id": "VswQfp534Xh2", + "outputId": "05043055-3af0-44b2-bc7a-fd4ffac463ba", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "source": [ + "from functools import lru_cache\n", + "import timeit\n", + "\n", + "def fib(n = 10):\n", + " if n == 0:\n", + " return 0\n", + " if n == 1:\n", + " return 1\n", + " return fib(n - 1) + fib(n - 2)\n", + "\n", + "@lru_cache()\n", + "def fib_opt(n = 10):\n", + " if n == 0:\n", + " return 0\n", + " if n == 1:\n", + " return 1\n", + " return fib(n - 1) + fib(n - 2)\n", + "\n", + "time1 = timeit.timeit(fib, number=100)\n", + "time2 = timeit.timeit(fib_opt, number=100)\n", + "print(time1, time2)" + ], + "execution_count": 1, + "outputs": [ + { + "output_type": "stream", + "text": [ + "0.0025363270000013927 3.17219999885765e-05\n" + ], + "name": "stdout" + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "xOc2_UGA4jLf" + }, + "source": [ + "The example above (using the fibonacci function) show the difference of time elapsed between a function using a cache and one that isn't." + ] + }, { "cell_type": "markdown", "metadata": { @@ -2095,4 +2161,4 @@ ] } ] -} \ No newline at end of file +}