Skip to content

Instantly share code, notes, and snippets.

@noahgift
Created November 5, 2018 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noahgift/c69200e05c057cf239fc7ea0be62e043 to your computer and use it in GitHub Desktop.
Save noahgift/c69200e05c057cf239fc7ea0be62e043 to your computer and use it in GitHub Desktop.
Public-Master-SafariOnline-Day1-Part1.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Public-Master-SafariOnline-Day1-Part1.ipynb",
"version": "0.3.2",
"provenance": [],
"collapsed_sections": [
"6HJtGuiKUYFU",
"BwmnQEziVQ9k",
"UYzPEDtnXlbx",
"CuJ2OPSZiewO",
"hlJXHUVq6391",
"9KQ2Cmcelcy-",
"qO-uoYUClvqr",
"WT4sChux989o",
"hQpf0vu_-Cnk",
"C95FIjW5-rJc",
"0F-jzlBYeOKC",
"Y_pr0ArieP7-",
"P3xpdAnD3aqo",
"1EBc2ohAonjw"
],
"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": [
"<a href=\"https://colab.research.google.com/gist/noahgift/c69200e05c057cf239fc7ea0be62e043/public-master-safarionline-day1-part1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"metadata": {
"id": "4J2lIggJLUMS",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# **Essential Machine Learning and Exploratory Data Analysis with Python and Jupyter Notebook**\n",
"\n"
]
},
{
"metadata": {
"id": "fu_dR92sSS5-",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Part 1.1-1.2**\n",
"\n",
"* [Part 1.1: Introductory Concepts in Python, IPython and Jupyter](https://colab.research.google.com/drive/1jPhYOyvweOJVW3Engci6GcnVEGd_UhGI#scrollTo=HWKUOfEBUMLS)\n",
"* [Part 1.2 Functions](https://colab.research.google.com/drive/1jPhYOyvweOJVW3Engci6GcnVEGd_UhGI#scrollTo=1wY-GUQc3te-)\n",
"* [References](https://colab.research.google.com/drive/1jPhYOyvweOJVW3Engci6GcnVEGd_UhGI#scrollTo=fQhEoJu1tNRe)\n",
"\n"
]
},
{
"metadata": {
"id": "c_Id55m6Jsbu",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Pragmatic AI Labs\n",
"\n"
]
},
{
"metadata": {
"id": "e5p96AqpSDZa",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"![alt text](https://paiml.com/images/logo_with_slogan_white_background.png)\n",
"\n",
"This notebook was produced by [Pragmatic AI Labs](https://paiml.com/). You can continue learning about these topics by:\n",
"\n",
"* Buying a copy of [Pragmatic AI: An Introduction to Cloud-Based Machine Learning](http://www.informit.com/store/pragmatic-ai-an-introduction-to-cloud-based-machine-9780134863917)\n",
"* Reading an online copy of [Pragmatic AI:Pragmatic AI: An Introduction to Cloud-Based Machine Learning](https://www.safaribooksonline.com/library/view/pragmatic-ai-an/9780134863924/)\n",
"* Watching video [Essential Machine Learning and AI with Python and Jupyter Notebook-Video-SafariOnline](https://www.safaribooksonline.com/videos/essential-machine-learning/9780135261118) on Safari Books Online.\n",
"* Purchasing video [Essential Machine Learning and AI with Python and Jupyter Notebook- Purchase Video](http://www.informit.com/store/essential-machine-learning-and-ai-with-python-and-jupyter-9780135261095)\n",
"* Viewing more content at [noahgift.com](https://noahgift.com/)\n"
]
},
{
"metadata": {
"id": "pBTeTbnRKG_k",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "HWKUOfEBUMLS",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Part 1.1: Introductory Concepts in Python, IPython and Jupyter\n",
"\n",
"* *[Read related material covered in Chapter 1 of Pragmatic AI](https://www.safaribooksonline.com/library/view/pragmatic-ai-an/9780134863924/ch01.xhtml#ch01)*\n",
"\n",
"* *[Watch video section: Lesson 1: Introducing Data Science Coding with Python Fundamentals](https://www.safaribooksonline.com/videos/essential-machine-learning/9780135261118/9780135261118-EMLA_01_01_00)*"
]
},
{
"metadata": {
"id": "nP_6tcHM7yFm",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Using IPython, Jupyter, and Python executable\n",
"\n",
"\n"
]
},
{
"metadata": {
"id": "n7JKyOrPkITH",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Using IPython\n",
"\n",
"Very similar to Jupyter, but run from terminal:\n",
"\n",
"* IPython predates Jupyter\n",
"* Both Jupyter and IPython accept *!ls -l* format to execute shell commands\n",
"\n"
]
},
{
"metadata": {
"id": "Pci2aotqPIME",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Jupyter Notebook\n",
"\n",
"\n",
"Many flavors of Jupyter Notebook. A few popular ones:\n",
"\n",
"![Jupyter](https://user-images.githubusercontent.com/58792/40282633-395be25c-5c27-11e8-9e40-357ea4216562.png =100x100)\n",
"![JupyterHug](https://user-images.githubusercontent.com/58792/40282632-387efe32-5c27-11e8-9f02-6f95f2fee223.png =150x150)\n",
"![Colab](https://user-images.githubusercontent.com/58792/40282631-384f8cf6-5c27-11e8-9209-3f0d22de0d81.png =100x100)\n",
"![Kaggle](https://user-images.githubusercontent.com/58792/40282634-3985c3a6-5c27-11e8-8c53-06fbdedce847.png =200x100)\n",
"![Sagemaker](https://user-images.githubusercontent.com/58792/40282635-39a3bdd4-5c27-11e8-81d5-6533a3b84771.png =200x100)\n",
"\n",
"#### Hosted Commercial Flavors\n",
"\n",
"* [Google Colaboratory](https://colab.research.google.com/notebook): Free\n",
"* [Kaggle](https://www.kaggle.com/): Free\n",
"\n",
"\n",
"#### Pure Open Source\n",
"\n",
"* [Jupyter](http://jupyter.org/) standalone, original\n",
"* [JupyterHub](https://github.com/jupyterhub/jupyterhub) multi-user, docker friendly\n",
"\n",
"#### Hybrid Solutions\n",
"\n",
"* Running Jupyter on [AWS Spot Instances](https://aws.amazon.com/ec2/spot/)\n",
"* [Google Data Lab](https://cloud.google.com/datalab/)\n",
"* [Azure Data Science Virtual Machines](https://azure.microsoft.com/en-us/services/virtual-machines/data-science-virtual-machines/)\n",
"* [AWS Sagemaker](https://aws.amazon.com/sagemaker/)\n",
"* [Azure Machine Learning Studio](https://studio.azureml.net/)\n"
]
},
{
"metadata": {
"id": "lh4tsf3-p-lw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Colab Notebook Key Features"
]
},
{
"metadata": {
"id": "V-xv1E3YqDK4",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"* Can enable both TPU and GPU runtimes\n",
"* Can upload regular Jupyter Notebooks into colab\n",
"* Can have a Google Drive Full of Colab Notebooks\n",
"* Can sync colab notebooks to Github \n",
"* Can connect to a [local runtime](https://research.google.com/colaboratory/local-runtimes.html)\n",
"* Can create [forms in Colab](https://colab.research.google.com/notebooks/forms.ipynb)\n",
"\n",
"\n",
"\n"
]
},
{
"metadata": {
"id": "Lgxm56T_u38j",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Upload to Colab"
]
},
{
"metadata": {
"id": "ww-HcdVwuwEM",
"colab_type": "code",
"colab": {
"resources": {
"http://localhost:8080/nbextensions/google.colab/files.js": {
"data": "Ly8gQ29weXJpZ2h0IDIwMTcgR29vZ2xlIExMQwovLwovLyBMaWNlbnNlZCB1bmRlciB0aGUgQXBhY2hlIExpY2Vuc2UsIFZlcnNpb24gMi4wICh0aGUgIkxpY2Vuc2UiKTsKLy8geW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLgovLyBZb3UgbWF5IG9idGFpbiBhIGNvcHkgb2YgdGhlIExpY2Vuc2UgYXQKLy8KLy8gICAgICBodHRwOi8vd3d3LmFwYWNoZS5vcmcvbGljZW5zZXMvTElDRU5TRS0yLjAKLy8KLy8gVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZQovLyBkaXN0cmlidXRlZCB1bmRlciB0aGUgTGljZW5zZSBpcyBkaXN0cmlidXRlZCBvbiBhbiAiQVMgSVMiIEJBU0lTLAovLyBXSVRIT1VUIFdBUlJBTlRJRVMgT1IgQ09ORElUSU9OUyBPRiBBTlkgS0lORCwgZWl0aGVyIGV4cHJlc3Mgb3IgaW1wbGllZC4KLy8gU2VlIHRoZSBMaWNlbnNlIGZvciB0aGUgc3BlY2lmaWMgbGFuZ3VhZ2UgZ292ZXJuaW5nIHBlcm1pc3Npb25zIGFuZAovLyBsaW1pdGF0aW9ucyB1bmRlciB0aGUgTGljZW5zZS4KCi8qKgogKiBAZmlsZW92ZXJ2aWV3IEhlbHBlcnMgZm9yIGdvb2dsZS5jb2xhYiBQeXRob24gbW9kdWxlLgogKi8KKGZ1bmN0aW9uKHNjb3BlKSB7CmZ1bmN0aW9uIHNwYW4odGV4dCwgc3R5bGVBdHRyaWJ1dGVzID0ge30pIHsKICBjb25zdCBlbGVtZW50ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnc3BhbicpOwogIGVsZW1lbnQudGV4dENvbnRlbnQgPSB0ZXh0OwogIGZvciAoY29uc3Qga2V5IG9mIE9iamVjdC5rZXlzKHN0eWxlQXR0cmlidXRlcykpIHsKICAgIGVsZW1lbnQuc3R5bGVba2V5XSA9IHN0eWxlQXR0cmlidXRlc1trZXldOwogIH0KICByZXR1cm4gZWxlbWVudDsKfQoKLy8gTWF4IG51bWJlciBvZiBieXRlcyB3aGljaCB3aWxsIGJlIHVwbG9hZGVkIGF0IGEgdGltZS4KY29uc3QgTUFYX1BBWUxPQURfU0laRSA9IDEwMCAqIDEwMjQ7Ci8vIE1heCBhbW91bnQgb2YgdGltZSB0byBibG9jayB3YWl0aW5nIGZvciB0aGUgdXNlci4KY29uc3QgRklMRV9DSEFOR0VfVElNRU9VVF9NUyA9IDMwICogMTAwMDsKCmZ1bmN0aW9uIF91cGxvYWRGaWxlcyhpbnB1dElkLCBvdXRwdXRJZCkgewogIGNvbnN0IHN0ZXBzID0gdXBsb2FkRmlsZXNTdGVwKGlucHV0SWQsIG91dHB1dElkKTsKICBjb25zdCBvdXRwdXRFbGVtZW50ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQob3V0cHV0SWQpOwogIC8vIENhY2hlIHN0ZXBzIG9uIHRoZSBvdXRwdXRFbGVtZW50IHRvIG1ha2UgaXQgYXZhaWxhYmxlIGZvciB0aGUgbmV4dCBjYWxsCiAgLy8gdG8gdXBsb2FkRmlsZXNDb250aW51ZSBmcm9tIFB5dGhvbi4KICBvdXRwdXRFbGVtZW50LnN0ZXBzID0gc3RlcHM7CgogIHJldHVybiBfdXBsb2FkRmlsZXNDb250aW51ZShvdXRwdXRJZCk7Cn0KCi8vIFRoaXMgaXMgcm91Z2hseSBhbiBhc3luYyBnZW5lcmF0b3IgKG5vdCBzdXBwb3J0ZWQgaW4gdGhlIGJyb3dzZXIgeWV0KSwKLy8gd2hlcmUgdGhlcmUgYXJlIG11bHRpcGxlIGFzeW5jaHJvbm91cyBzdGVwcyBhbmQgdGhlIFB5dGhvbiBzaWRlIGlzIGdvaW5nCi8vIHRvIHBvbGwgZm9yIGNvbXBsZXRpb24gb2YgZWFjaCBzdGVwLgovLyBUaGlzIHVzZXMgYSBQcm9taXNlIHRvIGJsb2NrIHRoZSBweXRob24gc2lkZSBvbiBjb21wbGV0aW9uIG9mIGVhY2ggc3RlcCwKLy8gdGhlbiBwYXNzZXMgdGhlIHJlc3VsdCBvZiB0aGUgcHJldmlvdXMgc3RlcCBhcyB0aGUgaW5wdXQgdG8gdGhlIG5leHQgc3RlcC4KZnVuY3Rpb24gX3VwbG9hZEZpbGVzQ29udGludWUob3V0cHV0SWQpIHsKICBjb25zdCBvdXRwdXRFbGVtZW50ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQob3V0cHV0SWQpOwogIGNvbnN0IHN0ZXBzID0gb3V0cHV0RWxlbWVudC5zdGVwczsKCiAgY29uc3QgbmV4dCA9IHN0ZXBzLm5leHQob3V0cHV0RWxlbWVudC5sYXN0UHJvbWlzZVZhbHVlKTsKICByZXR1cm4gUHJvbWlzZS5yZXNvbHZlKG5leHQudmFsdWUucHJvbWlzZSkudGhlbigodmFsdWUpID0+IHsKICAgIC8vIENhY2hlIHRoZSBsYXN0IHByb21pc2UgdmFsdWUgdG8gbWFrZSBpdCBhdmFpbGFibGUgdG8gdGhlIG5leHQKICAgIC8vIHN0ZXAgb2YgdGhlIGdlbmVyYXRvci4KICAgIG91dHB1dEVsZW1lbnQubGFzdFByb21pc2VWYWx1ZSA9IHZhbHVlOwogICAgcmV0dXJuIG5leHQudmFsdWUucmVzcG9uc2U7CiAgfSk7Cn0KCi8qKgogKiBHZW5lcmF0b3IgZnVuY3Rpb24gd2hpY2ggaXMgY2FsbGVkIGJldHdlZW4gZWFjaCBhc3luYyBzdGVwIG9mIHRoZSB1cGxvYWQKICogcHJvY2Vzcy4KICogQHBhcmFtIHtzdHJpbmd9IGlucHV0SWQgRWxlbWVudCBJRCBvZiB0aGUgaW5wdXQgZmlsZSBwaWNrZXIgZWxlbWVudC4KICogQHBhcmFtIHtzdHJpbmd9IG91dHB1dElkIEVsZW1lbnQgSUQgb2YgdGhlIG91dHB1dCBkaXNwbGF5LgogKiBAcmV0dXJuIHshSXRlcmFibGU8IU9iamVjdD59IEl0ZXJhYmxlIG9mIG5leHQgc3RlcHMuCiAqLwpmdW5jdGlvbiogdXBsb2FkRmlsZXNTdGVwKGlucHV0SWQsIG91dHB1dElkKSB7CiAgY29uc3QgaW5wdXRFbGVtZW50ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoaW5wdXRJZCk7CiAgaW5wdXRFbGVtZW50LmRpc2FibGVkID0gZmFsc2U7CgogIGNvbnN0IG91dHB1dEVsZW1lbnQgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZChvdXRwdXRJZCk7CiAgb3V0cHV0RWxlbWVudC5pbm5lckhUTUwgPSAnJzsKCiAgY29uc3QgcGlja2VkUHJvbWlzZSA9IG5ldyBQcm9taXNlKChyZXNvbHZlKSA9PiB7CiAgICBpbnB1dEVsZW1lbnQuYWRkRXZlbnRMaXN0ZW5lcignY2hhbmdlJywgKGUpID0+IHsKICAgICAgcmVzb2x2ZShlLnRhcmdldC5maWxlcyk7CiAgICB9KTsKICB9KTsKCiAgY29uc3QgY2FuY2VsID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnYnV0dG9uJyk7CiAgaW5wdXRFbGVtZW50LnBhcmVudEVsZW1lbnQuYXBwZW5kQ2hpbGQoY2FuY2VsKTsKICBjYW5jZWwudGV4dENvbnRlbnQgPSAnQ2FuY2VsIHVwbG9hZCc7CiAgY29uc3QgY2FuY2VsUHJvbWlzZSA9IG5ldyBQcm9taXNlKChyZXNvbHZlKSA9PiB7CiAgICBjYW5jZWwub25jbGljayA9ICgpID0+IHsKICAgICAgcmVzb2x2ZShudWxsKTsKICAgIH07CiAgfSk7CgogIC8vIENhbmNlbCB1cGxvYWQgaWYgdXNlciBoYXNuJ3QgcGlja2VkIGFueXRoaW5nIGluIHRpbWVvdXQuCiAgY29uc3QgdGltZW91dFByb21pc2UgPSBuZXcgUHJvbWlzZSgocmVzb2x2ZSkgPT4gewogICAgc2V0VGltZW91dCgoKSA9PiB7CiAgICAgIHJlc29sdmUobnVsbCk7CiAgICB9LCBGSUxFX0NIQU5HRV9USU1FT1VUX01TKTsKICB9KTsKCiAgLy8gV2FpdCBmb3IgdGhlIHVzZXIgdG8gcGljayB0aGUgZmlsZXMuCiAgY29uc3QgZmlsZXMgPSB5aWVsZCB7CiAgICBwcm9taXNlOiBQcm9taXNlLnJhY2UoW3BpY2tlZFByb21pc2UsIHRpbWVvdXRQcm9taXNlLCBjYW5jZWxQcm9taXNlXSksCiAgICByZXNwb25zZTogewogICAgICBhY3Rpb246ICdzdGFydGluZycsCiAgICB9CiAgfTsKCiAgaWYgKCFmaWxlcykgewogICAgcmV0dXJuIHsKICAgICAgcmVzcG9uc2U6IHsKICAgICAgICBhY3Rpb246ICdjb21wbGV0ZScsCiAgICAgIH0KICAgIH07CiAgfQoKICBjYW5jZWwucmVtb3ZlKCk7CgogIC8vIERpc2FibGUgdGhlIGlucHV0IGVsZW1lbnQgc2luY2UgZnVydGhlciBwaWNrcyBhcmUgbm90IGFsbG93ZWQuCiAgaW5wdXRFbGVtZW50LmRpc2FibGVkID0gdHJ1ZTsKCiAgZm9yIChjb25zdCBmaWxlIG9mIGZpbGVzKSB7CiAgICBjb25zdCBsaSA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2xpJyk7CiAgICBsaS5hcHBlbmQoc3BhbihmaWxlLm5hbWUsIHtmb250V2VpZ2h0OiAnYm9sZCd9KSk7CiAgICBsaS5hcHBlbmQoc3BhbigKICAgICAgICBgKCR7ZmlsZS50eXBlIHx8ICduL2EnfSkgLSAke2ZpbGUuc2l6ZX0gYnl0ZXMsIGAgKwogICAgICAgIGBsYXN0IG1vZGlmaWVkOiAkewogICAgICAgICAgICBmaWxlLmxhc3RNb2RpZmllZERhdGUgPyBmaWxlLmxhc3RNb2RpZmllZERhdGUudG9Mb2NhbGVEYXRlU3RyaW5nKCkgOgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAnbi9hJ30gLSBgKSk7CiAgICBjb25zdCBwZXJjZW50ID0gc3BhbignMCUgZG9uZScpOwogICAgbGkuYXBwZW5kQ2hpbGQocGVyY2VudCk7CgogICAgb3V0cHV0RWxlbWVudC5hcHBlbmRDaGlsZChsaSk7CgogICAgY29uc3QgZmlsZURhdGFQcm9taXNlID0gbmV3IFByb21pc2UoKHJlc29sdmUpID0+IHsKICAgICAgY29uc3QgcmVhZGVyID0gbmV3IEZpbGVSZWFkZXIoKTsKICAgICAgcmVhZGVyLm9ubG9hZCA9IChlKSA9PiB7CiAgICAgICAgcmVzb2x2ZShlLnRhcmdldC5yZXN1bHQpOwogICAgICB9OwogICAgICByZWFkZXIucmVhZEFzQXJyYXlCdWZmZXIoZmlsZSk7CiAgICB9KTsKICAgIC8vIFdhaXQgZm9yIHRoZSBkYXRhIHRvIGJlIHJlYWR5LgogICAgbGV0IGZpbGVEYXRhID0geWllbGQgewogICAgICBwcm9taXNlOiBmaWxlRGF0YVByb21pc2UsCiAgICAgIHJlc3BvbnNlOiB7CiAgICAgICAgYWN0aW9uOiAnY29udGludWUnLAogICAgICB9CiAgICB9OwoKICAgIC8vIFVzZSBhIGNodW5rZWQgc2VuZGluZyB0byBhdm9pZCBtZXNzYWdlIHNpemUgbGltaXRzLiBTZWUgYi82MjExNTY2MC4KICAgIGxldCBwb3NpdGlvbiA9IDA7CiAgICB3aGlsZSAocG9zaXRpb24gPCBmaWxlRGF0YS5ieXRlTGVuZ3RoKSB7CiAgICAgIGNvbnN0IGxlbmd0aCA9IE1hdGgubWluKGZpbGVEYXRhLmJ5dGVMZW5ndGggLSBwb3NpdGlvbiwgTUFYX1BBWUxPQURfU0laRSk7CiAgICAgIGNvbnN0IGNodW5rID0gbmV3IFVpbnQ4QXJyYXkoZmlsZURhdGEsIHBvc2l0aW9uLCBsZW5ndGgpOwogICAgICBwb3NpdGlvbiArPSBsZW5ndGg7CgogICAgICBjb25zdCBiYXNlNjQgPSBidG9hKFN0cmluZy5mcm9tQ2hhckNvZGUuYXBwbHkobnVsbCwgY2h1bmspKTsKICAgICAgeWllbGQgewogICAgICAgIHJlc3BvbnNlOiB7CiAgICAgICAgICBhY3Rpb246ICdhcHBlbmQnLAogICAgICAgICAgZmlsZTogZmlsZS5uYW1lLAogICAgICAgICAgZGF0YTogYmFzZTY0LAogICAgICAgIH0sCiAgICAgIH07CiAgICAgIHBlcmNlbnQudGV4dENvbnRlbnQgPQogICAgICAgICAgYCR7TWF0aC5yb3VuZCgocG9zaXRpb24gLyBmaWxlRGF0YS5ieXRlTGVuZ3RoKSAqIDEwMCl9JSBkb25lYDsKICAgIH0KICB9CgogIC8vIEFsbCBkb25lLgogIHlpZWxkIHsKICAgIHJlc3BvbnNlOiB7CiAgICAgIGFjdGlvbjogJ2NvbXBsZXRlJywKICAgIH0KICB9Owp9CgpzY29wZS5nb29nbGUgPSBzY29wZS5nb29nbGUgfHwge307CnNjb3BlLmdvb2dsZS5jb2xhYiA9IHNjb3BlLmdvb2dsZS5jb2xhYiB8fCB7fTsKc2NvcGUuZ29vZ2xlLmNvbGFiLl9maWxlcyA9IHsKICBfdXBsb2FkRmlsZXMsCiAgX3VwbG9hZEZpbGVzQ29udGludWUsCn07Cn0pKHNlbGYpOwo=",
"ok": true,
"headers": [
[
"content-type",
"application/javascript"
]
],
"status": 200,
"status_text": ""
}
},
"base_uri": "https://localhost:8080/",
"height": 36
},
"outputId": "a5ca7d1a-4536-4b99-dbb6-f41ad71f10c7"
},
"cell_type": "code",
"source": [
"from google.colab import files\n",
"uploaded = files.upload()"
],
"execution_count": 14,
"outputs": [
{
"output_type": "display_data",
"data": {
"text/html": [
"\n",
" <input type=\"file\" id=\"files-b00b7f33-8c15-4387-bd81-2ca99403af4f\" name=\"files[]\" multiple disabled />\n",
" <output id=\"result-b00b7f33-8c15-4387-bd81-2ca99403af4f\">\n",
" Upload widget is only available when the cell has been executed in the\n",
" current browser session. Please rerun this cell to enable.\n",
" </output>\n",
" <script src=\"/nbextensions/google.colab/files.js\"></script> "
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {
"tags": []
}
}
]
},
{
"metadata": {
"id": "0kmgxW7Sxa6j",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Forms in Colab"
]
},
{
"metadata": {
"id": "ZqHMr_brxdkA",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"Use_Python = False #@param [\"False\", \"True\"] {type:\"raw\"}"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "d1z9fz5_x_bf",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "e3580cab-a016-4a51-ce30-9d1ce7f8c2aa"
},
"cell_type": "code",
"source": [
"print(f\"You select it is {Use_Python} you use Python\")"
],
"execution_count": 18,
"outputs": [
{
"output_type": "stream",
"text": [
"You select it is True you use Python\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "kn-P-e_hjvK5",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Python executable\n",
"\n",
"Can run scripts, REPL and even run python statements with -c flag and semicolon to string together multiple statements"
]
},
{
"metadata": {
"id": "p2aDegQxjegv",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "ef6fd3d5-24bb-4b94-9512-4dd9d137b1fc"
},
"cell_type": "code",
"source": [
"!python -c \"import os;print(os.listdir())\""
],
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"text": [
"['.config', 'sample_data']\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "egHxTJUGNYCA",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "3e421488-c74c-4ae2-cc93-cb5dd2c8d3c3"
},
"cell_type": "code",
"source": [
"#this is how you capture input to a program\n",
"import sys;sys.argv"
],
"execution_count": 2,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py',\n",
" '-f',\n",
" '/root/.local/share/jupyter/runtime/kernel-a0b0350b-f3e1-4e60-87be-11bef5dc5d43.json']"
]
},
"metadata": {
"tags": []
},
"execution_count": 2
}
]
},
{
"metadata": {
"id": "6HJtGuiKUYFU",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Introductory Concepts\n",
"* **Procedural Statements**\n",
"* Strings and String Formatting\n",
"* Numbers and Arithmetic Operations\n",
"* Data Structures\n",
"\n"
]
},
{
"metadata": {
"id": "BwmnQEziVQ9k",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
" #### Procedural Statements\n",
" Procedural statements are literally statements that can be issued one line at a time. Below are types of procedural statements. These statements can be run in:\n",
" * Jupyter Notebook\n",
" * IPython shell\n",
" * Python interpreter\n",
" * Python scripts"
]
},
{
"metadata": {
"id": "yTePE3imVqfP",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Printing**"
]
},
{
"metadata": {
"id": "n1r0n2V3Vs70",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "58b64f49-8243-4e8c-93fe-e1d4b36df032"
},
"cell_type": "code",
"source": [
"print(\"Hello world\")\n"
],
"execution_count": 181,
"outputs": [
{
"output_type": "stream",
"text": [
"Hello world\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "8nUjNnApV6cC",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Create Variable and Use Variable**"
]
},
{
"metadata": {
"id": "mhjO2LpSVx9V",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "c563c3d0-1d82-4b57-9d0b-575be7dfd619"
},
"cell_type": "code",
"source": [
"variable = \"armbar\"; print(variable)"
],
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"text": [
"armbar\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "H004n8R-WDGF",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Multiple procedural statements**"
]
},
{
"metadata": {
"id": "xrZWZEFmV_bN",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "4a4e385b-a0ef-4c9c-daa1-43b2a1c1ea37"
},
"cell_type": "code",
"source": [
"attack_one = \"kimura\"\n",
"attack_two = \"arm triangle\"\n",
"print(\"In Brazilian Jiu Jitsu a common attack is a:\", attack_one)\n",
"print(\"Another common attack is a:\", attack_two)\n"
],
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"text": [
"In Brazilian Jiu Jitsu a common attack is a: kimura\n",
"Another common attack is a: arm triangle\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "6IiZ6RnLWKsq",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Adding Numbers**"
]
},
{
"metadata": {
"id": "h049FhlhWPRm",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "2cdb4229-c4ea-4473-f91c-0fe60c5594e3"
},
"cell_type": "code",
"source": [
"1+1"
],
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2"
]
},
"metadata": {
"tags": []
},
"execution_count": 10
}
]
},
{
"metadata": {
"id": "mlszsN87WmcO",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Adding Phrases**"
]
},
{
"metadata": {
"id": "FaE5GnCaWgbI",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "f9bbd81f-017c-40b0-b3c1-8a3febc74c11"
},
"cell_type": "code",
"source": [
"\"arm\" + \"bar\"+\"4\"+\"morestuff\""
],
"execution_count": 12,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'armbar4morestuff'"
]
},
"metadata": {
"tags": []
},
"execution_count": 12
}
]
},
{
"metadata": {
"id": "WSrfrIO1XYts",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Complex statements**\n",
"\n",
"More complex statements can be created that use data structures like the belts variable, which is a list."
]
},
{
"metadata": {
"id": "0nf0W0e3XSQS",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "43477e5e-1cf8-45a8-b476-2b62bc6beaa4"
},
"cell_type": "code",
"source": [
"belts = [\"white\", \"blue\", \"purple\", \"brown\", \"black\"]\n",
"for belt in belts:\n",
" if \"black\" in belt:\n",
" print(\"The belt I want to be is:\", belt)\n",
" else:\n",
" print(\"This is not the belt I want to end up at:\", belt)"
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"text": [
"This is not the belt I want to end up at: white\n",
"This is not the belt I want to end up at: blue\n",
"This is not the belt I want to end up at: purple\n",
"This is not the belt I want to end up at: brown\n",
"The belt I want to be is: black\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "UYzPEDtnXlbx",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Strings and String Formatting\n",
"\n",
"Strings are a sequence of characters and they are often programmatically formatted. Almost all Python programs have strings because they can be used to send messages to users who use the program. When creating strings there are few core concepts to understand:\n",
"\n",
"* Strings can be create with the single, double and triple/double quotes\n",
"* Strings are can be formatted\n",
"* One complication of strings is they can be encoded in several formats including unicode\n",
"* Many methods are available to operate on strings. In an editor or IPython shell you can see these methods by tab completion: \n",
"```\n",
"basic_string.\n",
" capitalize() format() islower() lower() rpartition() title() \n",
" casefold() format_map() isnumeric() lstrip() rsplit() translate() \n",
" center() index() isprintable() maketrans() rstrip() upper() \n",
" count() isalnum() isspace() partition() split() zfill() \n",
" encode() isalpha() istitle() replace() splitlines() \n",
" endswith() isdecimal() isupper() rfind() startswith() \n",
" expandtabs() isdigit() join() rindex() strip() \n",
" find() isidentifier() ljust() rjust() swapcase() \n",
"```"
]
},
{
"metadata": {
"id": "eHJX2ZFiXbFC",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "ce366ff9-b07f-49c9-b9e6-c482805b475e"
},
"cell_type": "code",
"source": [
"my_string = \"this is a string I am using\"\n",
"my_string.upper()\n"
],
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'THIS IS A STRING I AM USING'"
]
},
"metadata": {
"tags": []
},
"execution_count": 17
}
]
},
{
"metadata": {
"id": "8afQjS25YDvQ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Basic String**"
]
},
{
"metadata": {
"id": "yfhfvyIpX-pc",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"basic_string = \"Brazilian Jiu Jitsu\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "GMYqc-cKYJlL",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Splitting String**\n",
"\n",
"Turn a string in a list by splitting on spaces, or some other thing"
]
},
{
"metadata": {
"id": "eJaoPyTzYGSk",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "e40c663d-eb0f-459f-f9a1-b6ec3b328a41"
},
"cell_type": "code",
"source": [
"#split on spaces (default)\n",
"basic_string.split()"
],
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['Brazilian', 'Jiu', 'Jitsu']"
]
},
"metadata": {
"tags": []
},
"execution_count": 19
}
]
},
{
"metadata": {
"id": "z94Ajl0NZXBP",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "ea9c52c3-c159-4534-b616-6112c008d275"
},
"cell_type": "code",
"source": [
"#split on hyphen\n",
"string_with_hyphen = \"Brazilian-Jiu-Jitsu\"\n",
"string_with_hyphen.split(\"-\")"
],
"execution_count": 20,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['Brazilian', 'Jiu', 'Jitsu']"
]
},
"metadata": {
"tags": []
},
"execution_count": 20
}
]
},
{
"metadata": {
"id": "Ti9hySuGZbbX",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**All Capital**\n",
"\n",
"Turn a string into all Capital Letter"
]
},
{
"metadata": {
"id": "y2NEPM8PZZT_",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "24d05c9d-12e9-4cf3-f817-3108db781cea"
},
"cell_type": "code",
"source": [
"basic_string.upper()"
],
"execution_count": 22,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'BRAZILIAN JIU JITSU'"
]
},
"metadata": {
"tags": []
},
"execution_count": 22
}
]
},
{
"metadata": {
"id": "ZlifO6c4Zk5W",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Slicing Strings**\n",
"\n",
"Strings can be referenced by length and sliced"
]
},
{
"metadata": {
"id": "tBXlXz0TZh1Q",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "c31bc226-5afb-40c1-d579-5185e52dfcc6"
},
"cell_type": "code",
"source": [
"#Get first two characters\n",
"basic_string[:2]"
],
"execution_count": 26,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Br'"
]
},
"metadata": {
"tags": []
},
"execution_count": 26
}
]
},
{
"metadata": {
"id": "EhgFdziaZtPv",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "bd833c5f-e3f2-4d1c-9ec0-a9b6ecd3e948"
},
"cell_type": "code",
"source": [
"#Get length of string\n",
"len(basic_string)"
],
"execution_count": 24,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"19"
]
},
"metadata": {
"tags": []
},
"execution_count": 24
}
]
},
{
"metadata": {
"id": "lxvtolozZy1f",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Strings Can Be Added Together**"
]
},
{
"metadata": {
"id": "eIVgqMsRZvNQ",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "bf3799b2-e937-4db2-e70c-89323689a027"
},
"cell_type": "code",
"source": [
"basic_string + \" is my favorite Martial Art\""
],
"execution_count": 28,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Brazilian Jiu Jitsu is my favorite Martial Art'"
]
},
"metadata": {
"tags": []
},
"execution_count": 28
}
]
},
{
"metadata": {
"id": "trK8HQJ1Mx6E",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "97335320-e729-4616-e5d4-448911e4baa5"
},
"cell_type": "code",
"source": [
"\"this is a string format: %s\" % \"string format\""
],
"execution_count": 30,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'this is a string format: string format'"
]
},
"metadata": {
"tags": []
},
"execution_count": 30
}
]
},
{
"metadata": {
"id": "nNYxshNHZ6O8",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**F-Strings Can Be Formatted in More Complex Ways**\n",
"\n",
"One of the best ways to format a string in modern Python 3 is to use f-strings"
]
},
{
"metadata": {
"id": "u_NAcD5sZ1l4",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "e66a5a36-40e0-4955-e0f8-d2d2e563d811"
},
"cell_type": "code",
"source": [
"f'I love practicing my favorite Martial Art, {basic_string}'"
],
"execution_count": 32,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'I love practicing my favorite Martial Art, Brazilian Jiu Jitsu'"
]
},
"metadata": {
"tags": []
},
"execution_count": 32
}
]
},
{
"metadata": {
"id": "wlpMuwdmbui0",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Strings Can Use Triple Quotes to Wrap**"
]
},
{
"metadata": {
"id": "YWmNAWzqbT4k",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 54
},
"outputId": "ab44a227-e9fe-4788-a382-2975a940702a"
},
"cell_type": "code",
"source": [
"f\"\"\"\n",
"This phrase is multiple sentenances long.\n",
"There phrase can be formatted like simpler sentances,\n",
"for example, I can still talk about my favorite Martial Art {basic_string}\n",
"\"\"\""
],
"execution_count": 34,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'\\nThis phrase is multiple sentenances long.\\nThere phrase can be formatted like simpler sentances,\\nfor example, I can still talk about my favorite Martial Art Brazilian Jiu Jitsu\\n'"
]
},
"metadata": {
"tags": []
},
"execution_count": 34
}
]
},
{
"metadata": {
"id": "mBuMTMQWb239",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Line Breaks Can Be Removed with Replace**\n",
"\n",
"The last long line contained line breaks, which are the **\\n** character, and they can be removed by using the replace method"
]
},
{
"metadata": {
"id": "K8AVf6Pibz3H",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 54
},
"outputId": "6a69444b-7570-42a6-8e27-aaf84c442edf"
},
"cell_type": "code",
"source": [
"f\"\"\"\n",
"This phrase is multiple sentenances long.\n",
"There phrase can be formatted like simpler sentances,\n",
"for example, I can still talk about my favorite Martial Art {basic_string}\n",
"\"\"\".replace(\"\\n\", \"\")"
],
"execution_count": 37,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'This phrase is multiple sentenances long.There phrase can be formatted like simpler sentances,for example, I can still talk about my favorite Martial Art Brazilian Jiu Jitsu'"
]
},
"metadata": {
"tags": []
},
"execution_count": 37
}
]
},
{
"metadata": {
"id": "1sv8Q1ALePXM",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "eRmipgSocZ9i",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Numbers and Arithmetic Operations\n",
"\n",
"Python is also a built-in calculator. Without installing any additional libraries it can do many simple and complex arithmetic operations."
]
},
{
"metadata": {
"id": "xd6LxgEXcgP8",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Adding and Subtracting Numbers**"
]
},
{
"metadata": {
"id": "mKwZGBoMb6_A",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "98b2090e-9243-4c01-e43e-4bbb4775a683"
},
"cell_type": "code",
"source": [
"steps = (1+1)-1\n",
"print(f\"Two Steps Forward: One Step Back = {steps}\")"
],
"execution_count": 39,
"outputs": [
{
"output_type": "stream",
"text": [
"Two Steps Forward: One Step Back = 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "nMKS0ZYkdjvp",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Multiplication with Decimals**\n",
"\n",
"Can use float type to solve decimal problems"
]
},
{
"metadata": {
"id": "Xgrw0LDucinh",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "d0f9a13a-26c1-43ba-c689-e88a61edd3d0"
},
"cell_type": "code",
"source": [
"body_fat_percentage = 0.10\n",
"weight = 200\n",
"fat_total = body_fat_percentage * weight\n",
"print(f\"I weight 200lbs, and {fat_total}lbs of that is fat\")"
],
"execution_count": 41,
"outputs": [
{
"output_type": "stream",
"text": [
"I weight 200lbs, and 20.0lbs of that is fat\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "gjMkBnuxiCQW",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Can also use Decimal Library to set precision and deal with repeating decimal\n"
]
},
{
"metadata": {
"id": "GN_PYDuDiBHg",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "8e36ee16-4aa5-4f29-bc5c-200980fc904e"
},
"cell_type": "code",
"source": [
"from decimal import (Decimal, getcontext)\n",
"\n",
"getcontext().prec = 8\n",
"Decimal(1)/Decimal(3)\n",
"\n"
],
"execution_count": 43,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Decimal('0.33333333')"
]
},
"metadata": {
"tags": []
},
"execution_count": 43
}
]
},
{
"metadata": {
"id": "f1_B6OUrdxlU",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Using Exponents**\n",
"\n",
"Using the Python math library it is straightforward to call 2 to the 3rd power"
]
},
{
"metadata": {
"id": "Q2oC1HVhdmB9",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "1b6ad8b1-6fbe-447f-de14-c5dc6c7025ae"
},
"cell_type": "code",
"source": [
"import math\n",
"math.pow(2,3)"
],
"execution_count": 44,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"8.0"
]
},
"metadata": {
"tags": []
},
"execution_count": 44
}
]
},
{
"metadata": {
"id": "nkPcDry7jWt-",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Can also use built in exponent operator to accomplish same thing"
]
},
{
"metadata": {
"id": "9aV-R-DljXEj",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "a37ca77f-464c-4943-e411-3ef2c5ef00d1"
},
"cell_type": "code",
"source": [
"2**3"
],
"execution_count": 45,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"8"
]
},
"metadata": {
"tags": []
},
"execution_count": 45
}
]
},
{
"metadata": {
"id": "P6gOf9qtd6Nt",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Converting Between different numerical types**\n",
"\n",
"There are many numerical forms to be aware of in Python.\n",
"A couple of the most common are:\n",
"\n",
"* Integers\n",
"* Floats"
]
},
{
"metadata": {
"id": "XCWg7yX-d210",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "2fd2d663-ef4e-4f4b-b164-a16aca0a006f"
},
"cell_type": "code",
"source": [
"number = 100\n",
"num_type = type(number).__name__\n",
"print(f\"{number} is type [{num_type}]\")"
],
"execution_count": 47,
"outputs": [
{
"output_type": "stream",
"text": [
"100 is type [int]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "iW2f1Ik7eAzd",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "831383dd-bbc6-4184-f504-ffdbed15922d"
},
"cell_type": "code",
"source": [
"number = float(100)\n",
"num_type = type(number).__name__\n",
"print(f\"{number} is type [{num_type}]\")"
],
"execution_count": 48,
"outputs": [
{
"output_type": "stream",
"text": [
"100.0 is type [float]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "MrrFXb99gQ1Z",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Numbers can also be rounded**\n",
"\n",
"Python Built in round "
]
},
{
"metadata": {
"id": "Wjtnfol2iZDL",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "8860bf8a-ab50-4f49-f832-89cb453aaf69"
},
"cell_type": "code",
"source": [
"too_many_decimals = 1.912345897\n",
"round(too_many_decimals, 2)"
],
"execution_count": 50,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"1.91"
]
},
"metadata": {
"tags": []
},
"execution_count": 50
}
]
},
{
"metadata": {
"id": "SuJDUTLFWUJz",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Numpy round"
]
},
{
"metadata": {
"id": "PEabuAGGWXIF",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "1be80905-cad8-4b7d-937e-9ae91af63b9f"
},
"cell_type": "code",
"source": [
"import numpy as np\n",
"np.round(too_many_decimals, 2)"
],
"execution_count": 52,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"1.91"
]
},
"metadata": {
"tags": []
},
"execution_count": 52
}
]
},
{
"metadata": {
"id": "X3aHIe6qW8ab",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Pandas round"
]
},
{
"metadata": {
"id": "J-x_sjiZW-gB",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 80
},
"outputId": "520b8640-02fe-4d79-937b-de70d105610b"
},
"cell_type": "code",
"source": [
"import pandas as pd\n",
"df = pd.DataFrame([too_many_decimals], columns=[\"A\"], index=[\"first\"])\n",
"df.round(2)\n"
],
"execution_count": 54,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>A</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>first</th>\n",
" <td>1.91</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" A\n",
"first 1.91"
]
},
"metadata": {
"tags": []
},
"execution_count": 54
}
]
},
{
"metadata": {
"id": "elnncfa0XtOt",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Simple benchmark of all three (**Python**, **numpy** and **Pandas** round): using **%timeit**\n",
"\n",
"*Depending on what is getting rounded (i.e. a very large DataFrame, performance may very, so knowing how to benchmark performance is important with round) *\n"
]
},
{
"metadata": {
"id": "Yr1SXcF5Xw-L",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 177
},
"outputId": "4b6851d2-c7aa-4816-cdec-9967e821c5ec"
},
"cell_type": "code",
"source": [
"print(\"built in Python Round\")\n",
"%timeit round(too_many_decimals, 2)\n",
"\n",
"print(\"numpy round\")\n",
"%timeit np.round(too_many_decimals, 2)\n",
"\n",
"print(\"Pandas DataFrame round\")\n",
"%timeit df.round(2)"
],
"execution_count": 55,
"outputs": [
{
"output_type": "stream",
"text": [
"built in Python Round\n",
"The slowest run took 17.98 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"1000000 loops, best of 3: 547 ns per loop\n",
"numpy round\n",
"The slowest run took 11.27 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"100000 loops, best of 3: 7.91 µs per loop\n",
"Pandas DataFrame round\n",
"1000 loops, best of 3: 925 µs per loop\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "CuJ2OPSZiewO",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Data Structures\n",
"Python has a couple of core Data Structures that are used very frequently\n",
"\n",
"* Lists\n",
"* Dictionaries\n",
"\n",
"Dictionaries and lists are the real workhorses of Python, but there are also other Data Structers like tuples, sets, Counters, etc, that are worth exploring too."
]
},
{
"metadata": {
"id": "rYrg60aboNTc",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Python Dictionaries\n",
"\n",
"The workhorse of Python datastructures"
]
},
{
"metadata": {
"id": "TJgbX5wb7yHD",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Creating Python Dictionaries\n",
"\n",
"Creating Python Dictionaries can be done with* brackets {}*"
]
},
{
"metadata": {
"id": "IEi6YTS2iZj7",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "ffe3b84f-5e8f-47c6-8498-462db2941e42"
},
"cell_type": "code",
"source": [
"submissions = {\"armbar\": \"upper_body\", \n",
" \"arm_triangle\": \"upper_body\", \n",
" \"heel_hook\": \"lower_body\", \n",
" \"knee_bar\": \"lower_body\"}\n",
"submissions"
],
"execution_count": 59,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'arm_triangle': 'upper_body',\n",
" 'armbar': 'upper_body',\n",
" 'heel_hook': 'lower_body',\n",
" 'knee_bar': 'lower_body'}"
]
},
"metadata": {
"tags": []
},
"execution_count": 59
}
]
},
{
"metadata": {
"id": "4guKbqgfink8",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "dad9eb0e-2afa-4489-ec9f-e0cea933758b"
},
"cell_type": "code",
"source": [
"new_dict =dict(upper_body=\"lower_body\")\n",
"new_dict"
],
"execution_count": 61,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'upper_body': 'lower_body'}"
]
},
"metadata": {
"tags": []
},
"execution_count": 61
}
]
},
{
"metadata": {
"id": "TjNRS-YOjYxw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Using Python Dictionaries\n",
"A common dictionary usage pattern is to *iterate* on a dictionary by using the items method. In the example below the key and the value are printed:"
]
},
{
"metadata": {
"id": "kW1UR_yMi5bl",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "568da803-eacc-4bd9-89cd-99ee44cf1768"
},
"cell_type": "code",
"source": [
"for submission, body_part in submissions.items():\n",
" print(f\"The {submission} is an attack on the {body_part}\")"
],
"execution_count": 63,
"outputs": [
{
"output_type": "stream",
"text": [
"The armbar is an attack on the upper_body\n",
"The arm_triangle is an attack on the upper_body\n",
"The heel_hook is an attack on the lower_body\n",
"The knee_bar is an attack on the lower_body\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "5cue3xbzjfhF",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Dictionaries can also be used to *filter*. In the example below, only the submission attacks on the lower body are displayed:"
]
},
{
"metadata": {
"id": "buIoEo_Ajc1-",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "c11d1417-c562-4e8b-d401-52cd565c00b0"
},
"cell_type": "code",
"source": [
"print(f\"These are lower_body submission attacks in Brazilian Jiu Jitsu:\")\n",
"for submission, body_part in submissions.items():\n",
" if body_part == \"lower_body\":\n",
" print(submission)"
],
"execution_count": 65,
"outputs": [
{
"output_type": "stream",
"text": [
"These are lower_body submission attacks in Brazilian Jiu Jitsu:\n",
"heel_hook\n",
"knee_bar\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "9jkR5VTHjsc2",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Dictionary keys and values can also be selected with built in *keys() * and *values()* methods"
]
},
{
"metadata": {
"id": "SviUgzEfjjD-",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 72
},
"outputId": "ef7dadb0-b8c8-4a3e-9b9d-1ffe9f9356c7"
},
"cell_type": "code",
"source": [
"print(f\"These are keys: {submissions.keys()}\")\n",
"print(f\"These are values: {submissions.values()}\")"
],
"execution_count": 68,
"outputs": [
{
"output_type": "stream",
"text": [
"These are keys: dict_keys(['armbar', 'arm_triangle', 'heel_hook', 'knee_bar'])\n",
"These are values: dict_values(['upper_body', 'upper_body', 'lower_body', 'lower_body'])\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "sgPM6V_slmoy",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Key lookup is very performant, and one of the most common ways to use a dictionary."
]
},
{
"metadata": {
"id": "lOn5k2kRmk4K",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "a2f7ffb1-eca1-4e4e-f070-789807b8cbdf"
},
"cell_type": "code",
"source": [
"if \"armbar\" in submissions:\n",
" print(\"found key\")\n",
" "
],
"execution_count": 70,
"outputs": [
{
"output_type": "stream",
"text": [
"found key\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "ORI3ZxbqntAG",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 89
},
"outputId": "c6790938-af46-4a1d-dcc6-3be62a2f2bdd"
},
"cell_type": "code",
"source": [
"print(\"timing key membership\")\n",
"%timeit if \"armbar\" in submissions: pass "
],
"execution_count": 72,
"outputs": [
{
"output_type": "stream",
"text": [
"timing key membership\n",
"The slowest run took 38.38 times longer than the fastest. This could mean that an intermediate result is being cached.\n",
"10000000 loops, best of 3: 39.9 ns per loop\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "IyHkox1Rj66y",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Python Lists\n",
"\n",
"Lists are also very commonly used in Python. They allow for sequential collections. Lists can hold dictionaries, just as dictionaries can hold lists."
]
},
{
"metadata": {
"id": "Xo7IMK567yHQ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Creating Lists\n",
"\n",
"One way to create lists is with *[] syntax*"
]
},
{
"metadata": {
"id": "MI-S0FStj1o4",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"list_of_bjj_positions = [\"mount\", \"full-guard\", \"half-guard\", \n",
" \"turtle\", \"side-control\", \"rear-mount\", \n",
" \"knee-on-belly\", \"north-south\", \"open-guard\"]"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "WUgrRDDsoobr",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Another method os creating lists is with built in *list()* method\n"
]
},
{
"metadata": {
"id": "o-3IP2FOw9yi",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "0f8660d7-542f-46f9-aa10-d2869587db64"
},
"cell_type": "code",
"source": [
"bjj_dominant_positions = list()\n",
"bjj_dominant_positions.append(\"side-control\")\n",
"bjj_dominant_positions\n"
],
"execution_count": 74,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['side-control']"
]
},
"metadata": {
"tags": []
},
"execution_count": 74
}
]
},
{
"metadata": {
"id": "i1gjso964T1T",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Yet another way, very performant way to create lists is to use list comprehsion syntax"
]
},
{
"metadata": {
"id": "QeQt8XD_4T-D",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "fbe9c37b-3ded-4aaf-d776-6918c5a2fd66"
},
"cell_type": "code",
"source": [
"guards = \"full, half, open\"\n",
"guard_list = [f\"{guard}-guard\" for guard in guards.split(\",\")]\n",
"guard_list\n"
],
"execution_count": 77,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['full-guard', ' half-guard', ' open-guard']"
]
},
"metadata": {
"tags": []
},
"execution_count": 77
}
]
},
{
"metadata": {
"id": "CBDIYoFB7yHS",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Using Lists\n",
"\n",
"For loops are one of the simplist ways to use a list."
]
},
{
"metadata": {
"id": "EoFWVpKYj94o",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "b22c404a-cd47-49e0-cfdb-a44881a6dc1c"
},
"cell_type": "code",
"source": [
"for position in list_of_bjj_positions:\n",
" if \"full\" in position: #explore on your own \"guard\"\n",
" print(position)"
],
"execution_count": 84,
"outputs": [
{
"output_type": "stream",
"text": [
"full-guard\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "YAMxQJobkCy8",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Lists can also be used to select elements by slicing."
]
},
{
"metadata": {
"id": "Zi6PKsRIkAl_",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "22fe4c8a-e449-4fd6-936b-69fa60b81eba"
},
"cell_type": "code",
"source": [
"print(f'First position: {list_of_bjj_positions[:1]}')\n",
"print(f'Last position: {list_of_bjj_positions[-1:]}')\n",
"print(f'First three positions: {list_of_bjj_positions[0:3]}')"
],
"execution_count": 88,
"outputs": [
{
"output_type": "stream",
"text": [
"First position: ['mount']\n",
"Last position: ['open-guard']\n",
"First three positions: ['mount', 'full-guard', 'half-guard']\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "XgxwgI1I7Ex3",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Lists can also be used to unpack powerful, succinct statements when used with built-in functions like zip.\n"
]
},
{
"metadata": {
"id": "nkaMbTx77ddw",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "ac64003c-4fd4-4e82-9d10-f38f5cc31575"
},
"cell_type": "code",
"source": [
"bjj_position_matrix = [\n",
" [\"dominant\", \"top-mount\", \"back-mount\", \"side-control\"],\n",
" [\"neutral\", \"open-guard\", \"full-guard\", \"standing\"],\n",
" [\"weak\", \"turtle\", \"bottom-back-mount\", \"bottom-mount\"]\n",
"]\n",
"list(zip(*bjj_position_matrix))"
],
"execution_count": 91,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[('dominant', 'neutral', 'weak'),\n",
" ('top-mount', 'open-guard', 'turtle'),\n",
" ('back-mount', 'full-guard', 'bottom-back-mount'),\n",
" ('side-control', 'standing', 'bottom-mount')]"
]
},
"metadata": {
"tags": []
},
"execution_count": 91
}
]
},
{
"metadata": {
"id": "YXalviiD7yHZ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Python Sets\n",
"\n",
"Sets are unordered unique collections"
]
},
{
"metadata": {
"id": "1y5ahhJ699Gp",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Creating Python Sets\n",
"\n",
"Sets can be created by using built-in *sets()* method\n"
]
},
{
"metadata": {
"id": "ZT4d5Dxw9V4X",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "00f146b5-6f06-4345-a04f-e0193d2489e4"
},
"cell_type": "code",
"source": [
"unique_attacks = set((\"armbar\",\"armbar\"))\n",
"print(type(unique_attacks))\n",
"unique_attacks"
],
"execution_count": 92,
"outputs": [
{
"output_type": "stream",
"text": [
"<class 'set'>\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'armbar'}"
]
},
"metadata": {
"tags": []
},
"execution_count": 92
}
]
},
{
"metadata": {
"id": "Kj_JgH317yHZ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Using Sets\n",
"\n",
"One of the most powerful ways to use sets is to find the differences between to collections"
]
},
{
"metadata": {
"id": "zbAUyYgk_c0s",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "62786c31-662a-4868-eda6-df3f74b8fe26"
},
"cell_type": "code",
"source": [
"attacks_set_one = set((\"armbar\", \"kimura\", \"heal-hook\"))\n",
"attacks_set_two = set((\"toe-hold\", \"knee-bar\", \"heal-hook\"))\n",
"unique_set_one_attacks = attacks_set_one - attacks_set_two\n",
"print(f\"Unique Set One Attacks {unique_set_one_attacks}\")\n"
],
"execution_count": 96,
"outputs": [
{
"output_type": "stream",
"text": [
"Unique Set One Attacks {'kimura', 'armbar'}\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "ZTmBkJG0Xud_",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Question: \n",
"\n",
"Q: set() is used to select unique values. what is its performance for a deep learning large data sets. in large data sets, if set() is not performant enough, what are the alternatives?"
]
},
{
"metadata": {
"id": "1wY-GUQc3te-",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Part 1.2 Functions \n",
"\n",
"* *[Read related material covered in Chapter 1 (Functions Section) of Pragmatic AI](https://www.safaribooksonline.com/library/view/pragmatic-ai-an/9780134863924/ch01.xhtml#ch01lev1sub17)*\n",
"\n",
"* *[Watch video section 2: Writing and Applying Functions](https://www.safaribooksonline.com/videos/essential-machine-learning/9780135261118/9780135261118-EMLA_01_02_00)* \n",
"\n",
"* **Writing Functions**\n",
"* Function arguments: positional, keyword\n",
"* Functional Currying: Passing uncalled functions\n",
"* Functions that Yield\n",
"* Decorators: Functions that wrap other functions\n",
"* Making Classes Behave Like Functions\n",
"* Applying a Function to a Pandas DataFrame\n",
"* Writing Lambdas"
]
},
{
"metadata": {
"id": "8JmjS2H33wZP",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Writing Functions\n",
"Learning to write a function is the most fundamental skill to learn in Python. With a basic mastery of functions, it is possible to have an almost full command of the language."
]
},
{
"metadata": {
"id": "RHsiAy8N3-Cj",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Simple function**\n",
"\n",
"The simplest functions just return a value."
]
},
{
"metadata": {
"id": "YsngH1Yh4BP3",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def favorite_martial_art():\n",
" return \"bjj\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "hL4eSHZjjLSe",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "326cbc63-2989-4405-c867-187e46ca71e2"
},
"cell_type": "code",
"source": [
"print(favorite_martial_art())\n",
"# This is the same output\n",
"#my_variable = \"bjj\"\n",
"#my_variable"
],
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": [
"bjj\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "lq9VQm0V4BTE",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def myfunc():pass"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "CCYhFgvvjGHt",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"myfunc()\n",
"#result = myfunc()\n",
"#print(result)"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "AMPU657F4JWF",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Documenting Functions**\n",
"\n",
"It is a very good idea to document functions. \n",
"In Jupyter Notebook and IPython docstrings can be viewed by referring to the function with a ?. ie.\n",
"\n",
"```\n",
"In [2]: favorite_martial_art_with_docstring?\n",
"Signature: favorite_martial_art_with_docstring()\n",
"Docstring: This function returns the name of my favorite martial art\n",
"File: ~/src/functional_intro_to_python/<ipython-input-1-bef983c31735>\n",
"Type: function\n",
"```"
]
},
{
"metadata": {
"id": "ZKOHmIxg4Ply",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def favorite_martial_art_with_docstring():\n",
" \"\"\"This function returns the name of my favorite martial art\"\"\"\n",
" return \"bjj\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "8OW1SbDg4Rd1",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Docstrings of functions can be printed out by referring to *```__doc__```*** "
]
},
{
"metadata": {
"id": "SuI6CO-E4ViO",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "64bc2660-fa76-4a32-eb77-ee45b3852201"
},
"cell_type": "code",
"source": [
"favorite_martial_art_with_docstring.__doc__\n",
"#favorite_martial_art_with_docstring?\n"
],
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'This function returns the name of my favorite martial art'"
]
},
"metadata": {
"tags": []
},
"execution_count": 16
}
]
},
{
"metadata": {
"id": "ew4-TwH84YJa",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Function arguments: positional, keyword\n",
"\n",
"A function is most useful when arguments are passed to the function. New values for times are processed inside the function. This function is also a 'positional' argument, vs a keyword argument. Positional arguments are processed in the order they are created in."
]
},
{
"metadata": {
"id": "rxL-hyuL4aws",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def practice(times):\n",
" print(f\"I like to practice {times} times a day\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "WqDUN33f4cyf",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "d04515ad-3529-4274-9b25-2c755ba78ba2"
},
"cell_type": "code",
"source": [
"practice(2)"
],
"execution_count": 19,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice 2 times a day\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "C8h7Jo0y4ggH",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "701024f7-78d6-4c23-8e01-3546593a600a"
},
"cell_type": "code",
"source": [
"practice(3)"
],
"execution_count": 20,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice 3 times a day\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "LILwF-Nt4iTm",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Positional Arguments are processed in order**\n",
"\n",
"Note, *position* is the key to pay attention to.\n",
"\n"
]
},
{
"metadata": {
"id": "Aw6DSXR64oVx",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def practice(times, technique, duration):\n",
" print(f\"I like to practice {technique}, {times} times a day, for {duration} minutes\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "3Gq1XUkB4qtM",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "02907469-61aa-4ead-ef4e-5f818845e6ef"
},
"cell_type": "code",
"source": [
"practice(4, \"leg locks\", 45)"
],
"execution_count": 23,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice leg locks, 4 times a day, for 45 minutes\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Sv9WBxWzuWAy",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "994a5c79-781b-486f-9d6f-cae501f487ec"
},
"cell_type": "code",
"source": [
"#Order is important, now the entire is incorrect and prints out nonsense\n",
"practice(\"piano\", 7,60)"
],
"execution_count": 26,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice 7, piano times a day, for 60 minutes\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "ntX-r2Bp4uTw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Keyword Arguments are processed by key, value and can have default values**\n",
"\n",
"One handy feature of keyword arguments is that you can set defaults and only change the defaults you want to change."
]
},
{
"metadata": {
"id": "cSIg9mKs4zg_",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def practice(times=2, technique=\"kimura\", duration=60):\n",
" print(f\"I like to practice {technique}, {times} times a day, for {duration} minutes\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "Be5uDA_d41dg",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "f3b576ee-8180-4eb8-cd4c-e2d2dcb78079"
},
"cell_type": "code",
"source": [
"practice()"
],
"execution_count": 28,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice kimura, 2 times a day, for 60 minutes\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "qOwB-4Dz43HQ",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "70a60eb6-a1e9-4192-b4ac-3d1b7c1a4865"
},
"cell_type": "code",
"source": [
"practice(duration=90, technique=\"armbar\", times=4)"
],
"execution_count": 29,
"outputs": [
{
"output_type": "stream",
"text": [
"I like to practice armbar, 4 times a day, for 90 minutes\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "2wBL_tQ846Qd",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"*****args and ****kwargs\n",
"\n",
"allow dynamic argument passing to functions\n",
"Should be used with discretion because it can make code hard to understand"
]
},
{
"metadata": {
"id": "gJtpL1Ad5IUH",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def attack_techniques(**kwargs):\n",
" \"\"\"This accepts any number of keyword arguments\"\"\"\n",
" \n",
" for name, attack in kwargs.items():\n",
" print(f\"This is attack I would like to practice: {attack}\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "ODHgMleb5KVa",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "d8475e16-ace0-4683-c296-34ecbca0e7f9"
},
"cell_type": "code",
"source": [
"attack_techniques(arm_attack=\"kimura\", \n",
" leg_attack=\"straight_ankle_lock\", neck_attach=\"arm_triangle\")"
],
"execution_count": 32,
"outputs": [
{
"output_type": "stream",
"text": [
"This is attack I would like to practice: kimura\n",
"This is attack I would like to practice: straight_ankle_lock\n",
"This is attack I would like to practice: arm_triangle\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "rdvgasCNvwKt",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 104
},
"outputId": "eaa4f239-75ed-4eeb-9d8f-6b90594933bf"
},
"cell_type": "code",
"source": [
"#I also can pass as many things as I wants\n",
"attack_techniques(arm_attack=\"kimura\", \n",
" leg_attack=\"straight_ankle_lock\", \n",
" neck_attach=\"arm_triangle\",\n",
" attack4=\"rear nake choke\", attack5=\"key lock\")"
],
"execution_count": 35,
"outputs": [
{
"output_type": "stream",
"text": [
"This is attack I would like to practice: kimura\n",
"This is attack I would like to practice: straight_ankle_lock\n",
"This is attack I would like to practice: arm_triangle\n",
"This is attack I would like to practice: rear nake choke\n",
"This is attack I would like to practice: key lock\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "6Bd0PwiD5NnI",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**passing dictionary of keywords to function**\n",
"\n",
"**kwargs syntax can also be used to pass in arguments all at once"
]
},
{
"metadata": {
"id": "Rxjc3U7-5QlB",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"attacks = {\"arm_attack\":\"kimura\", \n",
" \"leg_attack\":\"straight_ankle_lock\", \n",
" \"neck_attach\":\"arm_triangle\"}"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "0BmMRBOC5SG-",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "d19aca87-3c48-4b1b-f67c-e0506c7516ea"
},
"cell_type": "code",
"source": [
"attack_techniques(**attacks)"
],
"execution_count": 38,
"outputs": [
{
"output_type": "stream",
"text": [
"This is attack I would like to practice: kimura\n",
"This is attack I would like to practice: straight_ankle_lock\n",
"This is attack I would like to practice: arm_triangle\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "3Srgz3C65Vdk",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Passing Around Functions**\n",
"\n",
"Object-Oriented programming is a very popular way to program, but it isn't the only style available in Python. For concurrency and for Data Science, functional programming fits as a complementary style.\n",
"\n",
"In the example, below a function can be used inside of another function by being passed into the function itself as an argument."
]
},
{
"metadata": {
"id": "inzYwQSq5XPy",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def attack_location(technique):\n",
" \"\"\"Return the location of an attack\"\"\"\n",
" \n",
" attacks = {\"kimura\": \"arm_attack\",\n",
" \"straight_ankle_lock\":\"leg_attack\", \n",
" \"arm_triangle\":\"neck_attach\"}\n",
" if technique in attacks:\n",
" return attacks[technique]\n",
" return \"Unknown\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "VfnYsD895ZFC",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "999f9651-2f8b-49d5-9432-7e93a26e66ee"
},
"cell_type": "code",
"source": [
"attack_location(\"kimura\")"
],
"execution_count": 41,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'arm_attack'"
]
},
"metadata": {
"tags": []
},
"execution_count": 41
}
]
},
{
"metadata": {
"id": "eK6NR4F-5aqT",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "48c92ac6-f752-4601-c1c4-ef968fd7b73d"
},
"cell_type": "code",
"source": [
"attack_location(\"bear hug\")"
],
"execution_count": 42,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'Unknown'"
]
},
"metadata": {
"tags": []
},
"execution_count": 42
}
]
},
{
"metadata": {
"id": "cOARK2b65f-k",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def multiple_attacks(attack_location_function):\n",
" \"\"\"Takes a function that categorizes attacks and returns location\"\"\"\n",
" \n",
" new_attacks_list = [\"rear_naked_choke\", \"americana\", \"kimura\"]\n",
" for attack in new_attacks_list:\n",
" attack_location = attack_location_function(attack)\n",
" print(f\"The location of attack {attack} is {attack_location}\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "WzgM8VU85iju",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "c31d3bc8-8e47-4c69-ee0d-c4d690da71d1"
},
"cell_type": "code",
"source": [
"multiple_attacks(attack_location)"
],
"execution_count": 44,
"outputs": [
{
"output_type": "stream",
"text": [
"The location of attack rear_naked_choke is Unknown\n",
"The location of attack americana is Unknown\n",
"The location of attack kimura is arm_attack\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "bCdDA35S5mQ4",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Closures and Functional Currying\n",
"\n",
"Closures are functions that contain other nested functions with state from outer function.\n",
"\n",
"In Python, a common way to use them is to keep track of the state. In the example below, the outer function, attack_counter keeps track of counts of attacks. The inner fuction attack_filter uses the \"nonlocal\" keyword in Python3, to modify the variable in the outer function.\n",
"\n",
"This approach is called \"functional currying\". It allows for a specialized function to be created from general functions. As shown below, this style of function could be the basis of a simple video game or maybe for the statistics crew of a mma match."
]
},
{
"metadata": {
"id": "QeG9UZfL6THb",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"#nonlocal cannot modify this variable\n",
"#lower_body_counter=5\n",
"def attack_counter():\n",
" \"\"\"Counts number of attacks on part of body\"\"\"\n",
" lower_body_counter = 0\n",
" upper_body_counter = 0\n",
" #print(lower_body_counter)\n",
" def attack_filter(attack):\n",
" nonlocal lower_body_counter\n",
" nonlocal upper_body_counter\n",
" attacks = {\"kimura\": \"upper_body\",\n",
" \"straight_ankle_lock\":\"lower_body\", \n",
" \"arm_triangle\":\"upper_body\",\n",
" \"keylock\": \"upper_body\",\n",
" \"knee_bar\": \"lower_body\"}\n",
" if attack in attacks:\n",
" if attacks[attack] == \"upper_body\":\n",
" upper_body_counter +=1\n",
" if attacks[attack] == \"lower_body\":\n",
" lower_body_counter +=1\n",
" print(f\"Upper Body Attacks {upper_body_counter}, Lower Body Attacks {lower_body_counter}\")\n",
" return attack_filter"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "YT_Tk-iT6WiR",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"fight = attack_counter()"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "J1p7hvGb6Y3m",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "27141134-2fb5-4c53-8c11-819bbd6e413a"
},
"cell_type": "code",
"source": [
"fight(\"kimura\")"
],
"execution_count": 47,
"outputs": [
{
"output_type": "stream",
"text": [
"Upper Body Attacks 1, Lower Body Attacks 0\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "gCoFnKDJ6aTS",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "9d4efb5b-1873-4ee1-d26b-aa0f4b8584c5"
},
"cell_type": "code",
"source": [
"fight(\"knee_bar\")"
],
"execution_count": 48,
"outputs": [
{
"output_type": "stream",
"text": [
"Upper Body Attacks 1, Lower Body Attacks 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "_3MRMBkS6bmy",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "31162357-1baa-430d-ac70-5988128efea6"
},
"cell_type": "code",
"source": [
"fight(\"keylock\")"
],
"execution_count": 49,
"outputs": [
{
"output_type": "stream",
"text": [
"Upper Body Attacks 2, Lower Body Attacks 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "hZx708yd7lpU",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Partial Functions\n",
"\n",
"Useful to partial assign default values to functions"
]
},
{
"metadata": {
"id": "fOhajVSK7oeX",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "547b37cb-a2da-469f-de4a-913b8a89fd95"
},
"cell_type": "code",
"source": [
"from functools import partial\n",
"\n",
"def multiple_attacks(attack_one, attack_two):\n",
" \"\"\"Performs two attacks\"\"\"\n",
" \n",
" print(f\"First Attack {attack_one}\")\n",
" print(f\"Second Attack {attack_two}\")\n",
" \n",
"attack_this = partial(multiple_attacks, \"kimura\")\n",
"type(attack_this)"
],
"execution_count": 51,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"functools.partial"
]
},
"metadata": {
"tags": []
},
"execution_count": 51
}
]
},
{
"metadata": {
"id": "ymZDwSka7rrh",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"By using this partial function, only one argument is needed"
]
},
{
"metadata": {
"id": "jJv6HePw7tkH",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "740b543c-a495-44ef-b576-4af368a8e7e0"
},
"cell_type": "code",
"source": [
"attack_this(\"knee-bar\")"
],
"execution_count": 52,
"outputs": [
{
"output_type": "stream",
"text": [
"First Attack kimura\n",
"Second Attack knee-bar\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "2CIWXwv27uPW",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Alternately, the original function can also be called with a different two attacks"
]
},
{
"metadata": {
"id": "QVudEj-h7wO_",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "0b3b8617-4f93-4164-c266-b01278d9bc38"
},
"cell_type": "code",
"source": [
"multiple_attacks(\"Darce Choke\", \"Bicep Slicer\")"
],
"execution_count": 53,
"outputs": [
{
"output_type": "stream",
"text": [
"First Attack Darce Choke\n",
"Second Attack Bicep Slicer\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "5-tKvYXt6ftS",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Lazy Evaluated Functions (Generators)\n",
"\n",
"A very useful style of programming is \"lazy evaluation\". A generator is an example of that. Generators yield an items at a time.\n",
"\n",
"The example below return an \"infinite\" random sequence of attacks. The lazy portion comes into play in that while there is an infinite amount of values, they are only returned when the function is called."
]
},
{
"metadata": {
"id": "P-hOWZyV6jCt",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def lazy_return_random_attacks():\n",
" \"\"\"Yield attacks each time\"\"\"\n",
" import random\n",
" attacks = {\"kimura\": \"upper_body\",\n",
" \"straight_ankle_lock\":\"lower_body\", \n",
" \"arm_triangle\":\"upper_body\",\n",
" \"keylock\": \"upper_body\",\n",
" \"knee_bar\": \"lower_body\"}\n",
" while True:\n",
" random_attack = random.choices(list(attacks.keys()))\n",
" yield random_attack"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "NrhrDOAL6u0b",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"attack = lazy_return_random_attacks()"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "NyxMi57a6wA4",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "51b851d7-a097-414b-a842-b6e1690fb2ca"
},
"cell_type": "code",
"source": [
"type(attack)"
],
"execution_count": 56,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"generator"
]
},
"metadata": {
"tags": []
},
"execution_count": 56
}
]
},
{
"metadata": {
"id": "0IxoCkJu6y-B",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "4919032d-73f0-4de9-e204-f52275ac28b9"
},
"cell_type": "code",
"source": [
"for _ in range(1):\n",
" print(next(attack))"
],
"execution_count": 66,
"outputs": [
{
"output_type": "stream",
"text": [
"['kimura']\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "hlJXHUVq6391",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Decorators: Functions that wrap other functions"
]
},
{
"metadata": {
"id": "9KQ2Cmcelcy-",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Randomized Sleep Decorator\n",
"\n",
"Another useful technique in Python is to use the decorator syntax to wrap one function with another function. In the example below, a decorator is written that adds random sleep to each function call. When combined with the previous \"infinite\" attack generator, it generates random sleeps between each function call."
]
},
{
"metadata": {
"id": "JvNzAVBT6695",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def randomized_speed_attack_decorator(function):\n",
" \"\"\"Randomizes the speed of attacks\"\"\"\n",
" \n",
" import time\n",
" import random\n",
" \n",
" def wrapper_func(*args, **kwargs):\n",
" sleep_time = random.randint(0,3)\n",
" print(f\"Attacking after {sleep_time} seconds\")\n",
" time.sleep(sleep_time)\n",
" return function(*args, **kwargs)\n",
" return wrapper_func"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "5BGrwIl96-PX",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"@randomized_speed_attack_decorator\n",
"def lazy_return_random_attacks():\n",
" \"\"\"Yield attacks each time\"\"\"\n",
" import random\n",
" attacks = {\"kimura\": \"upper_body\",\n",
" \"straight_ankle_lock\":\"lower_body\", \n",
" \"arm_triangle\":\"upper_body\",\n",
" \"keylock\": \"upper_body\",\n",
" \"knee_bar\": \"lower_body\"}\n",
" while True:\n",
" random_attack = random.choices(list(attacks.keys()))\n",
" yield random_attack"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "HAEY8I7M7AL5",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 191
},
"outputId": "284b48bf-e885-4714-e5ee-2e4213a9eb0d"
},
"cell_type": "code",
"source": [
"for _ in range(5):\n",
" print(next(lazy_return_random_attacks()))"
],
"execution_count": 71,
"outputs": [
{
"output_type": "stream",
"text": [
"Attacking after 0 seconds\n",
"['kimura']\n",
"Attacking after 2 seconds\n",
"['straight_ankle_lock']\n",
"Attacking after 0 seconds\n",
"['keylock']\n",
"Attacking after 2 seconds\n",
"['straight_ankle_lock']\n",
"Attacking after 3 seconds\n",
"['knee_bar']\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "qO-uoYUClvqr",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##### Timing Decorator"
]
},
{
"metadata": {
"id": "McePAV81l2Cm",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Using a decorator to time code is very common"
]
},
{
"metadata": {
"id": "pRtnp32Rl5jt",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"from functools import wraps\n",
"from time import time\n",
"\n",
"def timing(f):\n",
" @wraps(f)\n",
" def wrap(*args, **kw):\n",
" ts = time()\n",
" result = f(*args, **kw)\n",
" te = time()\n",
" print(f\"fun: {f.__name__}, args: [{args}, {kw}] took: {te-ts} sec\")\n",
" return result\n",
" return wrap"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "SFisqs8tmJer",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Using decorator to time execution of a function"
]
},
{
"metadata": {
"id": "h3B4RLEbmpie",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 142
},
"outputId": "bc0fb349-4487-4719-f642-9ff4bde7ebe4"
},
"cell_type": "code",
"source": [
"@timing\n",
"def some_attacks():\n",
" attack = lazy_return_random_attacks()\n",
" for _ in range(5):\n",
" print(next(attack))\n",
" \n",
"some_attacks()\n",
" "
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"text": [
"['knee_bar']\n",
"['knee_bar']\n",
"['kimura']\n",
"['kimura']\n",
"['straight_ankle_lock']\n",
"fun: some_attacks, args: [(), {}] took: 0.002496480941772461 sec\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "WT4sChux989o",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Making Classes Behave Like Functions\n",
"\n",
"Creating callable functions"
]
},
{
"metadata": {
"id": "y2ykyfI79_6E",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"class AttackFinder:\n",
" \"\"\"Finds the attack location\"\"\"\n",
" \n",
" \n",
" def __init__(self, attack):\n",
" self.attack = attack\n",
" \n",
" def __call__(self):\n",
" attacks = {\"kimura\": \"upper_body\",\n",
" \"straight_ankle_lock\":\"lower_body\", \n",
" \"arm_triangle\":\"upper_body\",\n",
" \"keylock\": \"upper_body\",\n",
" \"knee_bar\": \"lower_body\"}\n",
" if not self.attack in attacks:\n",
" return \"unknown location\"\n",
" return attacks[self.attack]\n",
" "
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "NKyd_XhOJCSk",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "b70425b9-0c5c-4263-97f7-fa2c59d3fbf1"
},
"cell_type": "code",
"source": [
"my_attack = AttackFinder(\"kimura\")\n",
"my_attack()"
],
"execution_count": 75,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'upper_body'"
]
},
"metadata": {
"tags": []
},
"execution_count": 75
}
]
},
{
"metadata": {
"id": "hQpf0vu_-Cnk",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Applying a Function to a Pandas DataFrame\n",
"\n",
"The final lesson on functions is to take this knowledge and use it on a DataFrame in Pandas. One of the more fundamental concepts in Pandas is use apply on a column vs iterating through all of the values. An example is shown below where all of the numbers are rounded to a whole digit."
]
},
{
"metadata": {
"id": "WLWOOacP-KDz",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 202
},
"outputId": "d78eb312-143a-45fe-a506-ca54945e78d7"
},
"cell_type": "code",
"source": [
"import pandas as pd\n",
"iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')\n",
"iris.head()"
],
"execution_count": 77,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sepal_length</th>\n",
" <th>sepal_width</th>\n",
" <th>petal_length</th>\n",
" <th>petal_width</th>\n",
" <th>species</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>5.1</td>\n",
" <td>3.5</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>4.9</td>\n",
" <td>3.0</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>4.7</td>\n",
" <td>3.2</td>\n",
" <td>1.3</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4.6</td>\n",
" <td>3.1</td>\n",
" <td>1.5</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5.0</td>\n",
" <td>3.6</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" sepal_length sepal_width petal_length petal_width species\n",
"0 5.1 3.5 1.4 0.2 setosa\n",
"1 4.9 3.0 1.4 0.2 setosa\n",
"2 4.7 3.2 1.3 0.2 setosa\n",
"3 4.6 3.1 1.5 0.2 setosa\n",
"4 5.0 3.6 1.4 0.2 setosa"
]
},
"metadata": {
"tags": []
},
"execution_count": 77
}
]
},
{
"metadata": {
"id": "S8jXLfVq-Nrb",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 222
},
"outputId": "03bdcc5f-b575-4a1d-9203-6812ee08555f"
},
"cell_type": "code",
"source": [
"iris['rounded_sepal_length'] = iris[['sepal_length']].apply(pd.Series.round)\n",
"iris.head()"
],
"execution_count": 78,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sepal_length</th>\n",
" <th>sepal_width</th>\n",
" <th>petal_length</th>\n",
" <th>petal_width</th>\n",
" <th>species</th>\n",
" <th>rounded_sepal_length</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>5.1</td>\n",
" <td>3.5</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>4.9</td>\n",
" <td>3.0</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>4.7</td>\n",
" <td>3.2</td>\n",
" <td>1.3</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4.6</td>\n",
" <td>3.1</td>\n",
" <td>1.5</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5.0</td>\n",
" <td>3.6</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" sepal_length sepal_width petal_length petal_width species \\\n",
"0 5.1 3.5 1.4 0.2 setosa \n",
"1 4.9 3.0 1.4 0.2 setosa \n",
"2 4.7 3.2 1.3 0.2 setosa \n",
"3 4.6 3.1 1.5 0.2 setosa \n",
"4 5.0 3.6 1.4 0.2 setosa \n",
"\n",
" rounded_sepal_length \n",
"0 5.0 \n",
"1 5.0 \n",
"2 5.0 \n",
"3 5.0 \n",
"4 5.0 "
]
},
"metadata": {
"tags": []
},
"execution_count": 78
}
]
},
{
"metadata": {
"id": "QrQiWvRC-QY9",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"This was done with a built in function, but a custom function can also be written and applied to a column. In the example below, the values are multiplied by 100. The alternative way to accomplish this would be to create a loop, transform the data and then write it back. In Pandas, it is straightforward and simple to apply custom functions instead."
]
},
{
"metadata": {
"id": "6WlPQ823-SMS",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 222
},
"outputId": "6bec8b25-cc28-44f5-e1b8-d01bf5562ee6"
},
"cell_type": "code",
"source": [
"def multiply_by_100(x):\n",
" \"\"\"Multiplies by 100\"\"\"\n",
" return x*100\n",
"iris['100x_sepal_length'] = iris[['sepal_length']].apply(multiply_by_100)\n",
"iris.head()"
],
"execution_count": 79,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>sepal_length</th>\n",
" <th>sepal_width</th>\n",
" <th>petal_length</th>\n",
" <th>petal_width</th>\n",
" <th>species</th>\n",
" <th>rounded_sepal_length</th>\n",
" <th>100x_sepal_length</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>5.1</td>\n",
" <td>3.5</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" <td>510.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>4.9</td>\n",
" <td>3.0</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" <td>490.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>4.7</td>\n",
" <td>3.2</td>\n",
" <td>1.3</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" <td>470.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4.6</td>\n",
" <td>3.1</td>\n",
" <td>1.5</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" <td>460.0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>5.0</td>\n",
" <td>3.6</td>\n",
" <td>1.4</td>\n",
" <td>0.2</td>\n",
" <td>setosa</td>\n",
" <td>5.0</td>\n",
" <td>500.0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" sepal_length sepal_width petal_length petal_width species \\\n",
"0 5.1 3.5 1.4 0.2 setosa \n",
"1 4.9 3.0 1.4 0.2 setosa \n",
"2 4.7 3.2 1.3 0.2 setosa \n",
"3 4.6 3.1 1.5 0.2 setosa \n",
"4 5.0 3.6 1.4 0.2 setosa \n",
"\n",
" rounded_sepal_length 100x_sepal_length \n",
"0 5.0 510.0 \n",
"1 5.0 490.0 \n",
"2 5.0 470.0 \n",
"3 5.0 460.0 \n",
"4 5.0 500.0 "
]
},
"metadata": {
"tags": []
},
"execution_count": 79
}
]
},
{
"metadata": {
"id": "gq3i_yeDWWHt",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"outputId": "8ea67505-8873-4f1b-d901-f11876837eb4"
},
"cell_type": "code",
"source": [
"#example of a smarter function\n",
"def smart_multiply_by_100(x):\n",
" if x > 5:\n",
" return 1\n",
" return x\n",
"\n",
"inputs = [1,2,6,10]\n",
"for input in inputs:\n",
" print(smart_multiply_by_100(input))\n",
" \n",
" "
],
"execution_count": 174,
"outputs": [
{
"output_type": "stream",
"text": [
"1\n",
"2\n",
"1\n",
"1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "6ox8_LbHW_vQ",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "C95FIjW5-rJc",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"#### Writing Lambdas\n",
"\n",
"Generally considered to be unnecessary. A Python lambda is an inline python and it can often lead to confusing code. \n"
]
},
{
"metadata": {
"id": "dEvuisbJ-tc2",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "b4a3761f-676b-44ba-e59f-a5567e621717"
},
"cell_type": "code",
"source": [
"func = lambda x: x**2\n",
"func(2)"
],
"execution_count": 80,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4"
]
},
"metadata": {
"tags": []
},
"execution_count": 80
}
]
},
{
"metadata": {
"id": "Cq9-b_1N-tpI",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "9ea440e0-f7b8-4e8c-b397-c42c82756df3"
},
"cell_type": "code",
"source": [
"def regular_func(x):\n",
" return x**2\n",
"\n",
"regular_func(2)"
],
"execution_count": 81,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4"
]
},
"metadata": {
"tags": []
},
"execution_count": 81
}
]
},
{
"metadata": {
"id": "FlIAJo2GK7KL",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def regular_func2(x):\n",
" \"\"\"This makes my variable go to the second power\"\"\"\n",
" return x**2"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "ZOMmTXtSLF9W",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
},
"outputId": "9c9d8f62-8e13-4765-b028-787d6c2ef860"
},
"cell_type": "code",
"source": [
"regular_func2(2)"
],
"execution_count": 180,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"4"
]
},
"metadata": {
"tags": []
},
"execution_count": 180
}
]
},
{
"metadata": {
"id": "rnXLQ6rZLKj5",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "fQhEoJu1tNRe",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## References"
]
},
{
"metadata": {
"id": "u6BaXDS7tQTD",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"* [Pragmatic AI: An Introduction to Cloud-Based Machine Learning-Physical Book](http://www.informit.com/store/pragmatic-ai-an-introduction-to-cloud-based-machine-9780134863917)\n",
"* [Pragmatic AI: Pragmatic AI: An Introduction to Cloud-Based Machine Learning-SafariOnline Book](https://www.safaribooksonline.com/library/view/pragmatic-ai-an/9780134863924/)\n",
"* [Essential Machine Learning and AI with Python and Jupyter Notebook-Video-SafariOnline](https://www.safaribooksonline.com/videos/essential-machine-learning/9780135261118)\n",
"* [Essential Machine Learning and AI with Python and Jupyter Notebook- Purchase Video](http://www.informit.com/store/essential-machine-learning-and-ai-with-python-and-jupyter-9780135261095)\n",
"* [noahgift.com](https://noahgift.com/)\n",
"* [paiml.com](https://paiml.com/)\n",
"* [Forbes: Here come the notebooks](https://www.forbes.com/sites/forbestechcouncil/2018/08/17/here-come-the-notebooks/#766563807609)\n",
"* [Circleci: Increase reliability in data science and ML projects](https://circleci.com/blog/increase-reliability-in-data-science-and-machine-learning-projects-with-circleci/)"
]
},
{
"metadata": {
"id": "0F-jzlBYeOKC",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## FAQ"
]
},
{
"metadata": {
"id": "Y_pr0ArieP7-",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Q: Why are Python Dictionaries so commonly used vs other data structures?"
]
},
{
"metadata": {
"id": "0k7pv2zFeZ2p",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"A: They are highly performant, easy to use, and flexible to program with"
]
},
{
"metadata": {
"id": "laOR73PneuHn",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "P3xpdAnD3aqo",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Q: Can use ‘+=1’ to keep adding to the variable instead of replacing it with ‘upper_body_counter = upper_body_counter + 1’?\n",
"\n",
"A: yes ```var +=1``` is *syntatic sugar*\n"
]
},
{
"metadata": {
"id": "XVYPRQHE3uUJ",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "c92ef341-5580-4c9f-8033-e04c35784a71"
},
"cell_type": "code",
"source": [
"count = 0\n",
"for i in range(3):\n",
" count +=1\n",
" print(count)"
],
"execution_count": 84,
"outputs": [
{
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "nKvaFr4T32T6",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "aa1f333e-e3c5-4f41-f694-0da6341e560f"
},
"cell_type": "code",
"source": [
"count = 3\n",
"for i in range(3):\n",
" count -=1\n",
" print(count)"
],
"execution_count": 85,
"outputs": [
{
"output_type": "stream",
"text": [
"2\n",
"1\n",
"0\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "nSZHcS0x37yc",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "5Kh5LRGT4CA1",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Q: Does a function with ‘return’ instead of using ‘print’ do the same thing?\n",
"\n",
"A: No, these are different mostly"
]
},
{
"metadata": {
"id": "3KmJMZvt4HLT",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "01a2f350-080f-4e3c-f6ec-8d6d4dc5bc42"
},
"cell_type": "code",
"source": [
"#in jupyter notebook, the last line prints automatically\n",
"var = \"blue\"\n",
"var"
],
"execution_count": 87,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'blue'"
]
},
"metadata": {
"tags": []
},
"execution_count": 87
}
]
},
{
"metadata": {
"id": "udtd73bF4Mbr",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def simple_color():\n",
" print(\"blue\")"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "3DRH-i3b4YWP",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "3fa220e0-2f1f-4fc2-e4b6-3ee018fcc279"
},
"cell_type": "code",
"source": [
"simple_color()"
],
"execution_count": 89,
"outputs": [
{
"output_type": "stream",
"text": [
"blue\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "0P7FTeA24aUE",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def simple_color_with_return():\n",
" return \"blue\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "Cy_LkeXc4iA4",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "09818a86-836b-430a-b837-dffcdc9e27bf"
},
"cell_type": "code",
"source": [
"simple_color_with_return()"
],
"execution_count": 91,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'blue'"
]
},
"metadata": {
"tags": []
},
"execution_count": 91
}
]
},
{
"metadata": {
"id": "rsvZudbT4lb8",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "7226c525-9b46-43b3-80c9-52c3dd354cfb"
},
"cell_type": "code",
"source": [
"if simple_color_with_return() == \"blue\":\n",
" print(\"green\")"
],
"execution_count": 92,
"outputs": [
{
"output_type": "stream",
"text": [
"green\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Fnq5fmgH4r0m",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 52
},
"outputId": "23da5e12-8918-45fe-eed1-8964ca08127f"
},
"cell_type": "code",
"source": [
"if simple_color() == \"blue\":\n",
" print(\"green\")\n",
"else:\n",
" print(\"the function had no return value\")"
],
"execution_count": 93,
"outputs": [
{
"output_type": "stream",
"text": [
"blue\n",
"the function had no return value\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "yV2-t0f742vt",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 69
},
"outputId": "41078e3e-5e2d-4cad-cf2c-84299cd93258"
},
"cell_type": "code",
"source": [
"simple_color() == None\n",
"simple_color() == \"blue\""
],
"execution_count": 95,
"outputs": [
{
"output_type": "stream",
"text": [
"blue\n",
"blue\n"
],
"name": "stdout"
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {
"tags": []
},
"execution_count": 95
}
]
},
{
"metadata": {
"id": "SBJKnr3h5P0L",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"A function with no Return value in python return None"
]
},
{
"metadata": {
"id": "kutwVeaP47b-",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def some_function_with_no_return():\n",
" var = \"blue\""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "dO9To4Kd5XdR",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "849480ec-f1d0-40af-a799-959814d252fb"
},
"cell_type": "code",
"source": [
"print(some_function_with_no_return())"
],
"execution_count": 97,
"outputs": [
{
"output_type": "stream",
"text": [
"None\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Cg0DIphT5bBQ",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"def some_function_with_return():\n",
" var = \"blue\"\n",
" return var"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "COjEYIo15f2g",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "bbfeb73e-d538-4772-e100-b1b65baffa87"
},
"cell_type": "code",
"source": [
"print(some_function_with_return())"
],
"execution_count": 100,
"outputs": [
{
"output_type": "stream",
"text": [
"blue\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "RekRZ8485hGB",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "8261d591-bad9-4f16-ea44-7710ac1eb98f"
},
"cell_type": "code",
"source": [
"result = some_function_with_return()\n",
"print(f\"The color that is my favorite is {result}, but I also like green\")"
],
"execution_count": 101,
"outputs": [
{
"output_type": "stream",
"text": [
"The color that is my favorite is blue, but I also like green\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "gYqiw7R45zm4",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "1EBc2ohAonjw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Homework Excercises\n",
"\n"
]
},
{
"metadata": {
"id": "fdm3kA-Fo4pI",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Can you Return random attacks without repeating?\n",
"\n",
"* keep track of previous calls and run random again if it finds a previous\n",
"\n",
"```\n",
"def lazy_return_random_attacks():\n",
" \"\"\"Yield attacks each time\"\"\"\n",
" import random\n",
" attacks = {\"kimura\": \"upper_body\",\n",
" \"straight_ankle_lock\":\"lower_body\", \n",
" \"arm_triangle\":\"upper_body\",\n",
" \"keylock\": \"upper_body\",\n",
" \"knee_bar\": \"lower_body\"}\n",
" while True:\n",
" random_attack = random.choices(list(attacks.keys()))\n",
" yield random_attack\n",
" \n",
"```\n",
"\n",
"pseudo code: if attack in previous_attacks:\n",
" ...new random\n",
" random_attack "
]
},
{
"metadata": {
"id": "jTj3ny5vo8GN",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
""
],
"execution_count": 0,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment