{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# A gentle guide to the Python features that I didn't know existed or was too afraid to use." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Lambda, map, filter, reduce\n", "\n", "The lambda keyword is used to create inline functions. `square_fn` and `square_ld` below are identical:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def square_fn(x):\n", " return x * x\n", "\n", "square_ld = lambda x: x * x\n", "\n", "for i in range(10):\n", " assert square_fn(i) == square_ld(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Its quick declaration makes `lambda` functions ideal for use in callbacks, and when functions are to be passed as arguments to other functions. They are especially useful when used in conjunction with functions like `map`, `filter`, and `reduce`.\n", "\n", "`map(fn, iterable)` applies the `fn` to all elements of the `iterable` (e.g. list, set, dictionary, tuple, string) and returns a map object." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.1111111111111111, 2263.0408163265306, 1.0851472983570953, 1.384083044982699, 0.4444444444444444]\n" ] } ], "source": [ "nums = [1/3, 333/7, 2323/2230, 40/34, 2/3]\n", "nums_squared = [num * num for num in nums]\n", "print(nums_squared)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the same as calling using `map` with a callback function." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.1111111111111111, 2263.0408163265306, 1.0851472983570953, 1.384083044982699, 0.4444444444444444]\n" ] } ], "source": [ "nums_squared_1 = map(square_fn, nums)\n", "nums_squared_2 = map(lambda x: x * x, nums)\n", "print(list(nums_squared_1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also use `map` with more than one iterable. For example, if you want to calculate the mean squared error of a simple linear function `f(x) = ax + b` with the true label `labels`, these two methods are equivalent:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.35089172119045514 0.35089172119045514\n" ] } ], "source": [ "a, b = 3, -0.5\n", "xs = [2, 3, 4, 5]\n", "labels = [6.4, 8.9, 10.9, 15.3]\n", "\n", "# Method 1: using a loop\n", "errors = []\n", "for i, x in enumerate(xs):\n", " errors.append((a * x + b - labels[i]) ** 2)\n", "result1 = sum(errors) ** 0.5 / len(xs)\n", "\n", "# Method 2: using map\n", "diffs = map(lambda x, y: (a * x + b - y) ** 2, xs, labels)\n", "result2 = sum(diffs) ** 0.5 / len(xs)\n", "\n", "print(result1, result2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that objects returned by `map` and `filter` are iterators, which means that their values aren't stored but generated as needed. After you've called `sum(diffs)`, `diffs` becomes empty. If you want to keep all elements in `diffs`, convert it to a list using `list(diffs)`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`filter(fn, iterable)` works the same way as `map`, except that `fn` returns a boolean value and `filter` returns all the elements of the `iterable` for which the `fn` returns True." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.8100000000000006, 0.6400000000000011]\n" ] } ], "source": [ "bad_preds = filter(lambda x: x > 0.5, errors)\n", "print(list(bad_preds))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`reduce(fn, iterable, initializer)` is used when we want to iteratively apply an operator to all elements in a list. For example, if we want to calculate the product of all elements in a list:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12.95564683272412\n" ] } ], "source": [ "product = 1\n", "for num in nums:\n", " product *= num\n", "print(product)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is equivalent to:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12.95564683272412\n" ] } ], "source": [ "from functools import reduce\n", "product = reduce(lambda x, y: x * y, nums)\n", "print(product)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Note on the performance of lambda functions\n", "\n", "Lambda functions are meant for one time use. Each time `lambda x: dosomething(x)` is called, the function has to be created, which hurts the performance if you call `lambda x: dosomething(x)` multiple times (e.g. when you pass it inside `reduce`).\n", "\n", "When you assign a name to the lambda function as in `fn = lambda x: dosomething(x)`, its performance is slightly slower than the same function defined using `def`, but the difference is negligible. See [here](https://stackoverflow.com/questions/26540885/lambda-is-slower-than-function-call-in-python-why).\n", "\n", "Even though I find lambdas cool, I personally recommend using named functions when you can for the sake of clarity." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. List manipulation\n", "Python lists are super cool.\n", "\n", "## 2.1 Unpacking\n", "We can unpack a list by each element like this:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 4\n" ] } ], "source": [ "elems = [1, 2, 3, 4]\n", "a, b, c, d = elems\n", "print(a, b, c, d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also unpack a list like this:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "[2, 3]\n", "4\n" ] } ], "source": [ "a, *new_elems, d = elems\n", "print(a)\n", "print(new_elems)\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.2 Slicing\n", "We know that we can reverse a list using `[::-1]`." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n" ] } ], "source": [ "elems = list(range(10))\n", "print(elems)\n", "print(elems[::-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The syntax `[x:y:z]` means \"take every `z`th element of a list from index `x` to index `y`\". When `z` is negative, it indicates going backwards. When `x` isn't specified, it defaults to the first element of the list in the direction you are traversing the list. When `y` isn't specified, it defaults to the last element of the list. So if we want to take every 2th element of a list, we use `[::2]`." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8]\n", "[8, 6, 4, 2, 0]\n" ] } ], "source": [ "evens = elems[::2]\n", "print(evens)\n", "\n", "reversed_evens = elems[-2::-2]\n", "print(reversed_evens)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use slicing to delete all the even numbers in the list." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 3, 5, 7, 9]\n" ] } ], "source": [ "del elems[::2]\n", "print(elems)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.3 Insertion\n", "We can change the value of an element in a list to another value." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 10, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "elems = list(range(10))\n", "elems[1] = 10\n", "print(elems)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to replace the element at an index with multiple elements, e.g. replace the value `1` with 3 values `20, 30, 40`:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 20, 30, 40, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "elems = list(range(10))\n", "elems[1:2] = [20, 30, 40]\n", "print(elems)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to insert 3 values `0.2, 0.3, 0.5` between element at index 0 and element at index 1:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 0.2, 0.3, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "elems = list(range(10))\n", "elems[1:1] = [0.2, 0.3, 0.5]\n", "print(elems)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.4 Flattening\n", "We can flatten a list of lists using `sum`." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list_of_lists = [[1], [2, 3], [4, 5, 6]]\n", "sum(list_of_lists, [])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we have nested lists, we can recursively flatten it. That's another beauty of lambda functions -- we can use it in the same line as its creation." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]\n", "flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]\n", "flatten(nested_lists)\n", "\n", "# This amazing line of code is from\n", "# https://github.com/sahands/python-by-example/blob/master/python-by-example.rst#flattening-lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.5 List vs generator\n", "To illustrate the difference between a list and a generator, let's look at an example of creating n-grams out of a list of tokens.\n", "\n", "One way to create n-grams is to use a sliding window." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[['i', 'want', 'to'],\n", " ['want', 'to', 'go'],\n", " ['to', 'go', 'to'],\n", " ['go', 'to', 'school']]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tokens = ['i', 'want', 'to', 'go', 'to', 'school']\n", "\n", "def ngrams(tokens, n):\n", " length = len(tokens)\n", " grams = []\n", " for i in range(length - n + 1):\n", " grams.append(tokens[i:i+n])\n", " return grams\n", "\n", "ngrams(tokens, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above example, we have to store all the n-grams at the same time. If the text has m tokens, then the memory requirement is `O(nm)`, which can be problematic when m is large.\n", "\n", "Instead of using a list to store all n-grams, we can use a generator that generates the next n-gram when it's asked for. This is known as lazy evaluation. We can make the function `ngrams` returns a generator using the keyword `yield`. Then the memory requirement is `O(m+n)`." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "['i', 'want', 'to']\n", "['want', 'to', 'go']\n", "['to', 'go', 'to']\n", "['go', 'to', 'school']\n" ] } ], "source": [ "def ngrams(tokens, n):\n", " length = len(tokens)\n", " for i in range(length - n + 1):\n", " yield tokens[i:i+n]\n", "\n", "ngrams_generator = ngrams(tokens, 3)\n", "print(ngrams_generator)\n", "for ngram in ngrams_generator:\n", " print(ngram)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another way to generate n-grams is to use slices to create lists: `[0, 1, ..., -n]`, `[1, 2, ..., -n+1]`, ..., `[n-1, n, ..., -1]`, and then `zip` them together." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "('i', 'want', 'to')\n", "('want', 'to', 'go')\n", "('to', 'go', 'to')\n", "('go', 'to', 'school')\n" ] } ], "source": [ "def ngrams(tokens, n):\n", " length = len(tokens)\n", " slices = (tokens[i:length-n+i+1] for i in range(n))\n", " return zip(*slices)\n", "\n", "ngrams_generator = ngrams(tokens, 3)\n", "print(ngrams_generator) # zip objects are generators\n", "for ngram in ngrams_generator:\n", " print(ngram)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that to create slices, we use `(tokens[...] for i in range(n))` instead of `[tokens[...] for i in range(n)]`. `[]` is the normal list comprehension that returns a list. `()` returns a generator." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. Classes and magic methods\n", "In Python, magic methods are prefixed and suffixed with the double underscore `__`, also known as dunder. The most wellknown magic method is probably `__init__`." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "class Node:\n", " \"\"\" A struct to denote the node of a binary tree.\n", " It contains a value and pointers to left and right children.\n", " \"\"\"\n", " def __init__(self, value, left=None, right=None):\n", " self.value = value\n", " self.left = left\n", " self.right = right" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we try to print out a Node object, however, it's not very interpretable." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.Node object at 0x10e1a8890>\n" ] } ], "source": [ "root = Node(5)\n", "print(root)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ideally, when user prints out a node, we want to print out the node's value and the values of its children if it has children. To do so, we use the magic method `__repr__`, which must return a printable object, like string." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value: 5, left: 4, right: None\n" ] } ], "source": [ "class Node:\n", " \"\"\" A struct to denote the node of a binary tree.\n", " It contains a value and pointers to left and right children.\n", " \"\"\"\n", " def __init__(self, value, left=None, right=None):\n", " self.value = value\n", " self.left = left\n", " self.right = right\n", " \n", " def __repr__(self): \n", " strings = [f'value: {self.value}']\n", " strings.append(f'left: {self.left.value}' if self.left else 'left: None')\n", " strings.append(f'right: {self.right.value}' if self.right else 'right: None')\n", " return ', '.join(strings)\n", "\n", "left = Node(4)\n", "root = Node(5, left)\n", "print(root)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'd also like to compare two nodes by comparing their values. To do so, we overload the operator `==` with `__eq__`, `<` with `__lt__`, and `>=` with `__ge__`." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "False\n" ] } ], "source": [ "class Node:\n", " \"\"\" A struct to denote the node of a binary tree.\n", " It contains a value and pointers to left and right children.\n", " \"\"\"\n", " def __init__(self, value, left=None, right=None):\n", " self.value = value\n", " self.left = left\n", " self.right = right\n", " \n", " def __eq__(self, other):\n", " return self.value == other.value\n", " \n", " def __lt__(self, other):\n", " return self.value < other.value\n", " \n", " def __ge__(self, other):\n", " return self.value >= other.value\n", "\n", "\n", "left = Node(4)\n", "root = Node(5, left)\n", "print(left == root)\n", "print(left < root)\n", "print(left >= root)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a comprehensive list of supported magic methods [here](https://www.tutorialsteacher.com/python/magic-methods-in-python) or see the official Python documentation [here](https://docs.python.org/3/reference/datamodel.html#special-method-names) (slightly harder to read).\n", "\n", "Some of the methods that I highly recommend:\n", "\n", "- `__len__`: to overload the `len()` function.\n", "- `__str__`: to overload the `str()` function.\n", "- `__iter__`: if you want to your objects to be iterators. This also allows you to call `next()` on your object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For classes like Node where we know for sure all the attributes they can support (in the case of Node, they are `value`, `left`, and `right`), we might want to use `__slots__` to denote those values for both performance boost and memory saving. For a comprehensive understanding of pros and cons of `__slots__`, see this [absolutely amazing answer by Aaron Hall on StackOverflow](https://stackoverflow.com/a/28059785/5029595)." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "class Node:\n", " \"\"\" A struct to denote the node of a binary tree.\n", " It contains a value and pointers to left and right children.\n", " \"\"\"\n", " __slots__ = ('value', 'left', 'right')\n", " def __init__(self, value, left=None, right=None):\n", " self.value = value\n", " self.left = left\n", " self.right = right" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. local namespace, object's attributes\n", "\n", "The `locals()` function returns a dictionary containing the variables defined in the local namespace." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'self': <__main__.Model1 object at 0x10f210590>, 'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}\n" ] } ], "source": [ "class Model1:\n", " def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):\n", " print(locals())\n", " self.hidden_size = hidden_size\n", " self.num_layers = num_layers\n", " self.learning_rate = learning_rate\n", "\n", "model1 = Model1()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All attributes of an object are stored in its `__dict__`." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model1.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that manually assigning each of the arguments to an attribute can be quite tiring when the list of the arguments is large. To avoid this, we can directly assign the list of arguments to the object's `__dict__`." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Model2:\n", " def __init__(self, hidden_size=100, num_layers=3, learning_rate=3e-4):\n", " params = locals()\n", " del params['self']\n", " self.__dict__ = params\n", "\n", "model2 = Model2()\n", "model2.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can be especially convenient when the object is initiated using the catch-all `**kwargs`." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'hidden_size': 100, 'num_layers': 3, 'learning_rate': 0.0003}" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Model3:\n", " def __init__(self, **kwargs):\n", " self.__dict__ = kwargs\n", "\n", "model3 = Model3(hidden_size=100, num_layers=3, learning_rate=3e-4)\n", "model3.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. Wildcard import\n", "Often, you run into this wildcard import `*` that looks something like this:\n", "\n", "`file.py`\n", " \n", " from parts import *\n", "\n", "This is irresponsible because it will import everything in module, even the imports of that module. For example, if `parts.py` looks like this:\n", "\n", "`parts.py`\n", "\n", " import numpy\n", " import tensorflow\n", " \n", " class Encoder:\n", " ...\n", " \n", " class Decoder:\n", " ...\n", " \n", " class Loss:\n", " ...\n", " \n", " def helper(*args, **kwargs):\n", " ...\n", " \n", " def utils(*args, **kwargs):\n", " ...\n", "\n", "Since `parts.py` doesn't have `__all__` specified, `file.py` will import Encoder, Decoder, Loss, utils, helper together with numpy and tensorflow.\n", "\n", "If we intend that only Encoder, Decoder, and Loss are ever to be imported and used in another module, we should specify that in `parts.py` using the `__all__` keyword.\n", "\n", "`parts.py`\n", " \n", " __all__ = ['Encoder', 'Decoder', 'Loss']\n", " import numpy\n", " import tensorflow\n", " \n", " class Encoder:\n", " ...\n", "\n", "Now, if some user irresponsibly does a wildcard import with `parts`, they can only import Encoder, Decoder, Loss. Personally, I also find `__all__` helpful as it gives me an overview of the module." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6. Decorator to time your functions\n", "\n", "It's often useful to know how long it takes a function to run, e.g. when you need to compare the performance of two algorithms that do the same thing. One naive way is to call `time.time()` at the begin and end of each function and print out the difference.\n", "\n", "For example: compare two algorithms to calculate the n-th Fibonacci number, one uses memoization and one doesn't." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "def fib_helper(n):\n", " if n < 2:\n", " return n\n", " return fib_helper(n - 1) + fib_helper(n - 2)\n", "\n", "def fib(n):\n", " \"\"\" fib is a wrapper function so that later we can change its behavior\n", " at the top level without affecting the behavior at every recursion step.\n", " \"\"\"\n", " return fib_helper(n)\n", "\n", "def fib_m_helper(n, computed):\n", " if n in computed:\n", " return computed[n]\n", " computed[n] = fib_m_helper(n - 1, computed) + fib_m_helper(n - 2, computed)\n", " return computed[n]\n", "\n", "def fib_m(n):\n", " return fib_m_helper(n, {0: 0, 1: 1})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's make sure that `fib` and `fib_m` are functionally equivalent." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "for n in range(20):\n", " assert fib(n) == fib_m(n)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Without memoization, it takes 0.267569 seconds.\n", "With memoization, it takes 0.0000713 seconds.\n" ] } ], "source": [ "import time\n", "\n", "start = time.time()\n", "fib(30)\n", "print(f'Without memoization, it takes {time.time() - start:7f} seconds.')\n", "\n", "start = time.time()\n", "fib_m(30)\n", "print(f'With memoization, it takes {time.time() - start:.7f} seconds.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to time multiple functions, it can be a drag having to write the same code over and over again. It'd be nice to have a way to specify how to change any function in the same way. In this case would be to call time.time() at the beginning and the end of each function, and print out the time difference.\n", "\n", "This is exactly what decorators do. They allow programmers to change the behavior of a function or class. Here's an example to create a decorator `timeit`." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "def timeit(fn): \n", " # *args and **kwargs are to support positional and named arguments of fn\n", " def get_time(*args, **kwargs): \n", " start = time.time() \n", " output = fn(*args, **kwargs)\n", " print(f\"Time taken in {fn.__name__}: {time.time() - start:.7f}\")\n", " return output # make sure that the decorator returns the output of fn\n", " return get_time " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Add the decorator `@timeit` to your functions." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "@timeit\n", "def fib(n):\n", " return fib_helper(n)\n", "\n", "@timeit\n", "def fib_m(n):\n", " return fib_m_helper(n, {0: 0, 1: 1})" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Time taken in fib: 0.2787242\n", "Time taken in fib_m: 0.0000138\n" ] }, { "data": { "text/plain": [ "832040" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fib(30)\n", "fib_m(30)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 7. Caching with @functools.lru_cache\n", "Memoization is a form of cache: we cache the previously calculated Fibonacci numbers so that we don't have to calculate them again.\n", "\n", "Caching is such an important technique that Python provides a built-in decorator to give your function the caching capacity. If you want `fib_helper` to reuse the previously calculated Fibonacci numbers, you can just add the decorator `lru_cache` from `functools`. `lru` stands for \"least recently used\". For more information on cache, see [here](https://docs.python.org/3/library/functools.html)." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "import functools\n", "\n", "@functools.lru_cache()\n", "def fib_helper(n):\n", " if n < 2:\n", " return n\n", " return fib_helper(n - 1) + fib_helper(n - 2)\n", "\n", "@timeit\n", "def fib(n):\n", " \"\"\" fib is a wrapper function so that later we can change its behavior\n", " at the top level without affecting the behavior at every recursion step.\n", " \"\"\"\n", " return fib_helper(n)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Time taken in fib: 0.0000412\n", "Time taken in fib_m: 0.0000281\n" ] }, { "data": { "text/plain": [ "12586269025" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fib(50)\n", "fib_m(50)" ] } ], "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.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }