{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "python.ipynb", "provenance": [], "collapsed_sections": [], "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "metadata": { "id": "nbWAdu9YXQ4m" }, "source": [ "##➛About this tutorial" ] }, { "cell_type": "markdown", "metadata": { "id": "LsZUmB7jXQ4o" }, "source": [ "Jan 17, 2020\n", "\n", "This Python and Numpy turorial (`part I - Python`) was adapted by [Badri Adhikari](https://badriadhikari.github.io/) from the original adaptation by [Volodymyr Kuleshov](http://web.stanford.edu/~kuleshov/) and [Isaac Caswell](https://symsys.stanford.edu/viewing/symsysaffiliate/21335) from the `CS231n` Python tutorial by Justin Johnson (http://cs231n.github.io/python-numpy-tutorial/). Expanded the broadcasting section by adapting [this tutorial](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)." ] }, { "cell_type": "markdown", "metadata": { "id": "2nYQalGqvGkW" }, "source": [ "##➛Google Colab and Notebook\n", "What is Google colab? Watch [this](https://www.youtube.com/watch?v=inN8seMm7UI) 3 minute video.\n", "* File ➛ Upload Notebook..\n", "* File ➛ Save a copy in Github..\n", "* File ➛ Save\n", "* File ➛ Download .ipynb\n", "* Edit ➛ Notebook settings (Runtime type & Hardware accelerator)\n", "* Edit ➛ Clear all outputs\n", "* Tools ➛ Settings ➛ Editor ➛ Show line numbers\n", "* Tools ➛ Site ➛ dark mode (careful with plots)\n", "* `+Code` vs `+Text`\n", "* View ➛ Table of contents\n", "* Share ➛ \"Anyone with the link can `view`\"\n", "* You can run multiple cells at once and go make your coffee.\n", "* Markdown [documentation](https://colab.research.google.com/notebooks/markdown_guide.ipynb)\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "j7qFBSsIjuWI" }, "source": [ "##➛Working with notebooks" ] }, { "cell_type": "code", "metadata": { "id": "OHk0aRazjdiZ" }, "source": [ "! nvidia-smi" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "lWdosV7BkDaW" }, "source": [ "Uploading and downloading files" ] }, { "cell_type": "code", "metadata": { "id": "yWEOJlr1jye6" }, "source": [ "from google.colab import files\n", "uploaded = files.upload()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "-ynmbubokGZJ" }, "source": [ "from google.colab import files\n", "files.download('example.csv')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Aj9R9OeFkSgt" }, "source": [ "! wget https://github.com/badriadhikari/AI-2020spring/raw/master/supporting_files/umsl.png" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "OF9JIYhykLZ5" }, "source": [ "! ls -l" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "eYX35-sDjbPT" }, "source": [ "! pip3 install mypackage" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "HOPOqlN4XQ4o" }, "source": [ "##➛Introduction to Python" ] }, { "cell_type": "markdown", "metadata": { "id": "1rDkZ6oHXQ4o" }, "source": [ "Python is a great `general-purpose programming language` on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a `powerful environment` for scientific computing.\n", "\n", "This tutorial will serve as a quick crash course on:\n", "* the Python programming language, and \n", "* the use of Python for scientific computing" ] }, { "cell_type": "markdown", "metadata": { "id": "pRm7wIxGXQ4p" }, "source": [ "In this tutorial, we will cover:\n", "\n", "* Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes\n", "* Numpy: Arrays, Array indexing, Datatypes, Array math, Broadcasting\n", "* Matplotlib: Plotting, Subplots, Images" ] }, { "cell_type": "markdown", "metadata": { "id": "4SRSiiFEXQ4x" }, "source": [ "##➛Python versions" ] }, { "cell_type": "markdown", "metadata": { "id": "fO0gBe0HXQ4y" }, "source": [ "* Two versions of Python are widely used - 2.x and 3.x \n", "* Python 3.0 introduced many **backwards-incompatible** changes to the language, so code written for 2.7 may not work under 3.4 and vice versa \n", "* You can check your Python version at the command line by running `python --version` \n", "* Support for Python2 expired at the end of 2019" ] }, { "cell_type": "code", "metadata": { "id": "W1p3yq28AFai" }, "source": [ "import platform\n", "print(platform.python_version())" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "dir-MjbhAR8c" }, "source": [ "# Throws an error in Python3\n", "print 'Hello Python'" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "GQnHWeUjAVdP" }, "source": [ "# Runs in both Python2 and Python3\n", "print ('Hello Python')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "cSRa04VrXQ4y" }, "source": [ "##➛Basic data types" ] }, { "cell_type": "markdown", "metadata": { "id": "_afjVBluXQ4z" }, "source": [ "####Numbers" ] }, { "cell_type": "markdown", "metadata": { "id": "82f00cksXQ40" }, "source": [ "Integers and floats work as you would expect from other languages:" ] }, { "cell_type": "code", "metadata": { "id": "2SXDdPYRXQ41" }, "source": [ "x = 3\n", "print( x )\n", "print( type(x) ) " ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Qk3L7BvxYJpz" }, "source": [ "**\"`type`\" is your screwdriver!** \n", "![](https://raw.githubusercontent.com/badriadhikari/AI-2020spring/master/supporting_files/screwdriver.png)" ] }, { "cell_type": "code", "metadata": { "id": "ZQoLFbK5XQ44" }, "source": [ "print( x + 1 ) # Addition;\n", "print( x - 1 ) # Subtraction;\n", "print( x * 2 ) # Multiplication;\n", "print( x ** 2 ) # Exponentiation;" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "FjSY2pQ-XQ47" }, "source": [ "x += 1\n", "print(x)\n", "x *= 2\n", "print(x)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "ndqxe4fQXQ5A" }, "source": [ "y = 2.5\n", "print( type(y) )\n", "print( y, y + 1, y * 2, y ** 2 )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "2iDyBx-9XQ5D" }, "source": [ "Note that unlike many languages, Python does not have unary increment `(x++)` or decrement `(x--)` operators.\n", "\n", "Python also has built-in types for long integers and complex numbers:\n", "* Python 2 has int, **long**, float, and complex data types [documentation](https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex).\n", "* Python 3 has int, float, and complex data types [documentation](https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex)." ] }, { "cell_type": "code", "metadata": { "id": "hxndyMLaCqXV" }, "source": [ "# Automatically creates a variable of the required type (in Python2)\n", "x = 100000000000000000\n", "print(type(x))\n", "x = 10000000000000000000\n", "print(type(x))\n", "x = 10.0\n", "print(type(x))\n", "x = -1.0 + 1.0j\n", "print(type(x))\n", "x = '10.0'\n", "print(type(x))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "jUjxzfzBcUrW" }, "source": [ "Python 2 has two integer types int and long. These have been unified in **Python 3**, so there is now **only one type, int**. Read more [here](http://python3porting.com/differences.html)." ] }, { "cell_type": "code", "metadata": { "id": "MZGwQJUAb1mP" }, "source": [ "x = long(x)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "t_nUElzZXQ5E" }, "source": [ "####Booleans" ] }, { "cell_type": "markdown", "metadata": { "id": "NwjLxkTlXQ5E" }, "source": [ "Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (`&&`, `||`, etc.):" ] }, { "cell_type": "code", "metadata": { "id": "IDE3pJQsXQ5F" }, "source": [ "t, f = True, False\n", "print(type(t))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "DwlctmbWXQ5H" }, "source": [ "Now we let's look at the operations:" ] }, { "cell_type": "code", "metadata": { "id": "02IRTOguXQ5J" }, "source": [ "print( t and f ) # Logical AND;\n", "print( t or f ) # Logical OR;\n", "print( not t ) # Logical NOT;\n", "print( t != f ) # Logical XOR;" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "CPfOR3Y6fAOK" }, "source": [ "#### Bitwise vs Logical Operators" ] }, { "cell_type": "code", "metadata": { "id": "TA-UKX1Hefy5" }, "source": [ "print( t & f ) # Bitwise AND (Not usually used)\n", "print( t | f ) # Bitwise OR (Not usually used)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "b0EPQUm6fTTO" }, "source": [ "print( 0 < 1 & 0 < 2 )\n", "print( 0 < 1 and 0 < 2 )\n", "# This is because the precedence of & and 'and'\n", "# & has higher precedence than <; 'and' has lower precedence than <" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "jXXGs88hXQ5L" }, "source": [ "####Strings" ] }, { "cell_type": "code", "metadata": { "id": "4YyzMC3SXQ5N" }, "source": [ "hello = 'hello' # String literals can use single quotes\n", "world = \"world\" # or double quotes; it does not matter.\n", "again = \"\"\"Hello\n", "learning python\n", " there\"\"\" # or even triple double quotes.\n", "\n", "print( hello, len(hello) )\n", "print(again)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "VcHkWQfdXQ5P" }, "source": [ "hw = hello + ' ' + world # String concatenation\n", "print( hw, hello, var2, var3, ) # Space in the middle" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "FBV5XbwCXQ5T" }, "source": [ "print('%13s %13s %d' % (hello, world, 12) ) # sprintf style string formatting, not very readable :(" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "RmBlB6Z0s2zJ" }, "source": [ "print(f\"I want to say {hello} to the {world}!\") # Python3's f-Strings" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "8QpwarB1gMyu" }, "source": [ "print(hello + world + str(12) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "1q_f8ODmXQ5X" }, "source": [ "String objects have a bunch of useful methods; for example:" ] }, { "cell_type": "code", "metadata": { "id": "ZLFvceXrXQ5X" }, "source": [ "s = \"hello\"\n", "print( s.capitalize() ) # Capitalize a string; prints \"Hello\"\n", "print( s.upper() ) # Convert a string to uppercase; prints \"HELLO\"\n", "print( s.rjust(7) ) # Right-justify a string, padding with spaces; prints \" hello\"\n", "print( s.center(7) ) # Center a string, padding with spaces; prints \" hello \"\n", "print( s.replace('l', '(ell)') ) # Replace all instances of one substring with another;\n", "\n", "print( ' world '.strip() ) # Strip leading and trailing whitespace; prints \"world\"\n", "\n", "s = \"hello class good evening\"\n", "cols = s.split() # Automatically detects multiple spaces \n", "print( cols[0], cols[2] )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "keAJIjudXQ5b" }, "source": [ "String methods [documentation](https://docs.python.org/3/library/stdtypes.html#string-methods)." ] }, { "cell_type": "markdown", "metadata": { "id": "ztYIS510XQ5c" }, "source": [ "##➛Containers" ] }, { "cell_type": "markdown", "metadata": { "id": "VVf3dJE_XQ5c" }, "source": [ "Python includes several built-in container types: lists, dictionaries, sets, and tuples." ] }, { "cell_type": "markdown", "metadata": { "id": "KFiKvWJ5XQ5d" }, "source": [ "####Lists" ] }, { "cell_type": "markdown", "metadata": { "id": "EAy4pH3ZXQ5d" }, "source": [ "A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:" ] }, { "cell_type": "code", "metadata": { "id": "RzroUsjqXQ5e" }, "source": [ "xs = [3, 1, 1, 2] # Create a list\n", "print( xs, xs[2] )\n", "print( xs[-1] ) # Negative indices count from the end of the list\n", "print( xs[-2] )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "X5pEMMzeXQ5g" }, "source": [ "xs[2] = 'foo' # Lists can contain elements of different types\n", "print( xs )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "teRFTgObXQ5j" }, "source": [ "xs.append('bar') # Add a new element to the end of the list\n", "print( xs )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "FP0offuYXQ5l" }, "source": [ "x = xs.pop() # Remove and return the last element of the list\n", "print( x, xs )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "EAmuDMpikTiT" }, "source": [ "xs = [3, 1, 5, 1, 3, 2]\n", "xs2 = [10, 11]\n", "xs.append(xs2)\n", "print( xs )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "1WknhcpXklnk" }, "source": [ "xs_another = [100, 1000, 200]\n", "xs.extend(xs_another) # Add one list to another list\n", "print(xs)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "UOdv25tEgZPC" }, "source": [ "**\"`extend`\" vs \"`append`\" !** \n", "![](https://raw.githubusercontent.com/badriadhikari/AI-2020spring/master/supporting_files/danger.png?raw=true)" ] }, { "cell_type": "markdown", "metadata": { "id": "7KbSCmYgXQ5o" }, "source": [ "Lists [documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)." ] }, { "cell_type": "markdown", "metadata": { "id": "Ry0LQEFcXQ5p" }, "source": [ "####Slicing" ] }, { "cell_type": "markdown", "metadata": { "id": "uA5vSltZXQ5q" }, "source": [ "In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:" ] }, { "cell_type": "code", "metadata": { "id": "hcBov6ISXQ5r" }, "source": [ "nums = range(5) # range is a built-in function that creates a list of integers\n", "print( nums ) # In Python2 this would print an actual list, in Python3 it returns an iterator\n", "print(type(nums))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "iK6jtqQKlArT" }, "source": [ "**Your Python2 code that has `range` may throw errors in Python3!** \n", "![](https://raw.githubusercontent.com/badriadhikari/AI-2020spring/master/supporting_files/danger.png?raw=true)\n" ] }, { "cell_type": "code", "metadata": { "id": "IjcXWErFjFX3" }, "source": [ "nums = [0, 1, 2, 3, 4]\n", "print( nums[2:4] ) # Get a slice from index 2 to 4 (exclusive)\n", "print( nums[2:] ) # Get a slice from index 2 to the end\n", "print( nums[:2] ) # Get a slice from the start to index 2 (exclusive)\n", "print( nums[:] ) # Get a slice of the whole list\n", "print( nums[:-1] ) # Slice indices can be negative\n", "nums[2:4] = [8, 8, 23, 56, 9] # Assign a new sublist to a slice\n", "print( nums ) " ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "y6WiMgTJXQ5t" }, "source": [ "####Loops" ] }, { "cell_type": "markdown", "metadata": { "id": "57xYARSuXQ5u" }, "source": [ "You can loop over the elements of a list like this:" ] }, { "cell_type": "code", "metadata": { "id": "0_PdlQJkXQ5w" }, "source": [ "animals = ['cat', 'dog', 'monkey']\n", "for animal in animals:\n", " print(animal)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "NP6t-hbSXQ5z" }, "source": [ "If you want access to the index of each element within the body of a loop, use the built-in `enumerate` function:" ] }, { "cell_type": "code", "metadata": { "id": "ylWRNU54XQ5z" }, "source": [ "animals = ['cat', 'dog', 'monkey']\n", "for idx, animal in enumerate(animals):\n", " print( '#%d: %s' % (idx + 1, animal) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "jw0uTFaxXQ52" }, "source": [ "####List comprehensions" ] }, { "cell_type": "markdown", "metadata": { "id": "qQKaqK2cXQ53" }, "source": [ "When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:" ] }, { "cell_type": "code", "metadata": { "id": "1-HdKEUhXQ54" }, "source": [ "nums = [0, 1, 2, 3, 4]\n", "squares = []\n", "for x in nums:\n", " squares.append(x ** 2)\n", "print( squares )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "fZJYuvZRXQ58" }, "source": [ "You can make this code simpler using a list comprehension:" ] }, { "cell_type": "code", "metadata": { "id": "2rIlXVmwXQ59" }, "source": [ "nums = [0, 1, 2, 3, 4]\n", "squares = [x ** 2 for x in nums]\n", "print(squares)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "vC8VH9LIXQ5_" }, "source": [ "List comprehensions can also contain conditions:" ] }, { "cell_type": "markdown", "metadata": { "id": "Z8xkFTSkpGdv" }, "source": [ "![](https://raw.githubusercontent.com/badriadhikari/AI-2020spring/master/supporting_files/important.png?raw=true)" ] }, { "cell_type": "code", "metadata": { "id": "QgE-sC9BXQ5_" }, "source": [ "nums = [0, 1, 2, 3, 4]\n", "even_squares = [x ** 2 for x in nums if x % 2 == 0]\n", "print(even_squares)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "TPJBdw85XQ6B" }, "source": [ "####Dictionaries" ] }, { "cell_type": "markdown", "metadata": { "id": "btzZxdQfXQ6C" }, "source": [ "A dictionary stores (key, value) pairs, similar to a `Map` in Java or an object in Javascript. You can use it like this:" ] }, { "cell_type": "code", "metadata": { "id": "3P46_qEuXQ6C" }, "source": [ "d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data\n", "print( d['cat'] ) # Get an entry from a dictionary\n", "print( 'cat' in d ) # Check if a dictionary has a given key" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "YjoSzydtXQ6F" }, "source": [ "d['fish'] = 'wet' # Set an entry in a dictionary\n", "print( d['fish'] ) " ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Cdo3HU59XQ6I" }, "source": [ "print( d['monkey'] )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "eDYsPRTDXQ6L" }, "source": [ "print( d.get('monkey', 'N/A') ) # Get an element with a default\n", "print( d.get('fish', 'N/A') ) # Get an element with a default" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "UMw3PcKeXQ6R" }, "source": [ "del d['fish'] # Remove an element from a dictionary\n", "print(d.get('fish', 'N/A')) # \"fish\" is no longer a key; prints \"N/A\"" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "z0zr6CpNXQ6U" }, "source": [ "Dictionaries [documentation](https://docs.python.org/3/library/stdtypes.html#dict)." ] }, { "cell_type": "markdown", "metadata": { "id": "Tjt2xjLEXQ6V" }, "source": [ "It is easy to iterate over the keys in a dictionary:" ] }, { "cell_type": "code", "metadata": { "id": "tbW77WMFXQ6V" }, "source": [ "d = {'person': 2, 'cat': 4, 'spider': 8}\n", "for animal in d:\n", " legs = d[animal]\n", " print( 'A %s has %d legs' % (animal, legs) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "3pTvBOxzXQ6X" }, "source": [ "If you want access to keys and their corresponding values, use the `.items()` method:" ] }, { "cell_type": "code", "metadata": { "id": "1P80hmoZXQ6X" }, "source": [ "d = {'person': 2, 'cat': 4, 'spider': 8}\n", "for animal, legs in d.items():\n", " print( 'A %s has %d legs' % (animal, legs) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "yfSvxkl5lwlm" }, "source": [ "If you want access to keys and their corresponding values (sorted by keys/values):" ] }, { "cell_type": "code", "metadata": { "id": "-Ljj9v0jl2lR" }, "source": [ "d = {'a': 2, 'c': 4, 'd': 1, 'b': 10}\n", "for animal, legs in sorted(d.items(), key = lambda x: x[0]):\n", " print( '%s - %d ' % (animal, legs) )\n", "\n", "print ('')\n", "for animal, legs in sorted(d.items(), key = lambda x: x[1]):\n", " print( '%s - %d ' % (animal, legs) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "IZmHjamEXQ6Z" }, "source": [ "**Dictionary comprehensions:** These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:" ] }, { "cell_type": "markdown", "metadata": { "id": "YnRi9u2Krh4G" }, "source": [ "![](https://raw.githubusercontent.com/badriadhikari/AI-2020spring/master/supporting_files/important.png?raw=true)" ] }, { "cell_type": "code", "metadata": { "id": "c0wXeLnaXQ6a" }, "source": [ "nums = [0, 1, 2, 3, 4]\n", "even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\n", "print( even_num_to_square )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "IxxzhgB3tr7v" }, "source": [ "**Why do we need dictionary comprehension?**" ] }, { "cell_type": "markdown", "metadata": { "id": "V49dt6GEXQ6c" }, "source": [ "####Sets" ] }, { "cell_type": "markdown", "metadata": { "id": "FmAjrkH6XQ6c" }, "source": [ "A set is an unordered collection of distinct elements. As a simple example, consider the following:" ] }, { "cell_type": "code", "metadata": { "id": "ebHHrClIXQ6d" }, "source": [ "animals = { 'cat', 'dog', 'cat' }\n", "print(animals)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Qwt6flA8virK" }, "source": [ "animals = [ 'cat', 'dog', 'cat' ]\n", "print(animals)\n", "animals = set(animals) # We can also use the 'set' function to create a set\n", "print(animals)" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "d5TigXB3XQ6i" }, "source": [ "animals.add('fish') # Add an element to a set\n", "print( 'fish' in animals )\n", "print( len(animals) ) # Number of elements in a set;" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "hhcWh5LcXQ6k" }, "source": [ "animals.add('cat') # Adding an element that is already in the set does nothing\n", "print( len(animals) ) \n", "animals.remove('cat') # Remove an element from a set\n", "print( len(animals) ) " ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "JfTWe_0HXQ6n" }, "source": [ "_Loops_: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:" ] }, { "cell_type": "code", "metadata": { "id": "07oATwP4XQ6o" }, "source": [ "animals = {'cat', 'dog', 'fish'}\n", "for idx, animal in enumerate(animals):\n", " print( '#%d: %s' % (idx + 1, animal) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "tTZDaXv6XQ6r" }, "source": [ "Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:" ] }, { "cell_type": "code", "metadata": { "id": "DAO5OB8HXQ6s" }, "source": [ "from math import sqrt\n", "myset = {int(sqrt(x)) for x in range(30)}\n", "print(myset)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "cO6T1WNsXQ6u" }, "source": [ "####Tuples" ] }, { "cell_type": "markdown", "metadata": { "id": "os-pRTcbXQ6v" }, "source": [ "A tuple is an (`immutable`) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that **tuples can be used as keys in dictionaries and as elements of sets, while lists cannot**. Here is a trivial example:" ] }, { "cell_type": "code", "metadata": { "id": "yZGpvDRaXQ6v" }, "source": [ "d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys\n", "print (d)\n", "t = (5, 6) # Create a tuple\n", "print( type(t) )\n", "print( d[t] ) \n", "print( d[(1, 2)] )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "DASvGl8rXQ6x" }, "source": [ "t[0] = 1 # immutable" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "OrmQO2aUXQ6y" }, "source": [ "##➛Functions" ] }, { "cell_type": "markdown", "metadata": { "id": "aNP1YVnAXQ6z" }, "source": [ "Python functions are defined using the `def` keyword. For example:" ] }, { "cell_type": "code", "metadata": { "id": "WTb__k8_XQ6z" }, "source": [ "def sign(x):\n", " if x > 0:\n", " return 'positive'\n", " elif x < 0:\n", " return 'negative'\n", " else:\n", " return 'zero'\n", "\n", "for x in [-1, 0, 1]:\n", " print( sign(x) )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "CW9qbYRaXQ60" }, "source": [ "We will often define functions to take optional keyword arguments, like this:" ] }, { "cell_type": "code", "metadata": { "id": "1DlqyU-4XQ61" }, "source": [ "def hello(name, loud = False):\n", " if loud:\n", " print( 'HELLO, %s' % name.upper() )\n", " else:\n", " print( 'Hello, %s!' % name )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "7OmGk6NLOjGo" }, "source": [ "hello()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "dWoNBVOzOlGz" }, "source": [ "hello('Fred')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "6q6FYqIEOo45" }, "source": [ "hello('Fred', True)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "P-1G2Pq-OxYk" }, "source": [ "**What is wrong with the following function's arguments?** \n", "Note: A `parameter` is variable in the declaration of function. `Argument` is the actual value of this variable that gets passed to function." ] }, { "cell_type": "code", "metadata": { "id": "WoPXu9rzOvUi" }, "source": [ "def hello(name, loud = False):\n", " if loud:\n", " print( 'HELLO, %s' % name.upper() )\n", " else:\n", " print( 'Hello, %s!' % name )" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "KSt1OzWQXQ62" }, "source": [ "##➛Classes" ] }, { "cell_type": "markdown", "metadata": { "id": "7DI0qDVUXQ63" }, "source": [ "* All classes create objects, and all objects contain characteristics called **attributes** \n", "* The **first argument of a method is `self`** - this is just a convention: the name `self` has absolutely no special meaning\n", "\n", "Syntax for defining classes:" ] }, { "cell_type": "code", "metadata": { "id": "7o6jsXVtXQ64" }, "source": [ "class A:\n", " def print_something(self):\n", " print( 'something' )\n", "\n", "a = A()\n", "a.print_something()" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "ohwcR-KWSLbs" }, "source": [ "class Greeter:\n", " name = \"\"\n", " # Constructor (optional but needed for any initialization )\n", " def __init__(self, name):\n", " self.name = name # Create an instance variable\n", "\n", " # Instance method\n", " def greet(self, loud = False):\n", " if loud:\n", " print( 'HELLO' )\n", " else:\n", " print( 'Hello' )" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "1o8dUPh2RzpO" }, "source": [ "g = Greeter('Fred') # Construct an instance of the Greeter class\n", "g.greet() # Call an instance method\n", "g.greet(loud=True) # Call an instance method" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "Y1nO6DmA4pS9" }, "source": [ "" ], "execution_count": null, "outputs": [] } ] }