├── .gitignore ├── LICENSE ├── README.md ├── week_1 ├── day_1_lab.ipynb ├── day_1_lecture.ipynb ├── day_2_lab.ipynb ├── day_2_variables.ipynb ├── day_3_lab.ipynb ├── day_3_lists.ipynb ├── day_4_dictionaries.ipynb ├── day_4_lab.ipynb ├── day_5_if_statements.ipynb └── day_5_lab.ipynb ├── week_2 ├── data │ ├── Bubble-sort-example.gif │ └── panda.jpg ├── day_1_lab.ipynb ├── day_1_lecture.ipynb ├── day_2_lab.ipynb ├── day_2_lecture.ipynb ├── day_3_lab.ipynb ├── day_3_lecture.ipynb ├── day_4_lab.ipynb └── day_4_lecture.ipynb ├── week_3 ├── day_1_assets │ ├── Cartesian_Product_qtl1.svg │ └── Permutations_RGB.svg ├── day_1_lab.ipynb ├── day_1_lecture.ipynb ├── day_2_assets │ ├── bbq_event-DictWriter.csv │ ├── bbq_event.csv │ ├── bbq_event.json │ ├── bbq_event.txt │ ├── incorrect_cols.csv │ ├── incorrect_cols.txt │ ├── incorrect_row_entry.csv │ ├── incorrect_row_entry.txt │ ├── lab │ │ └── pulled_pork_recipe.txt │ ├── test.txt │ └── tuple_test.txt ├── day_2_lab.ipynb ├── day_2_lecture.ipynb ├── day_3_assets │ ├── bbq_notification.txt │ ├── event_tables │ │ ├── bbq_event_1.csv │ │ └── bbq_event_2.csv │ └── lab.zip ├── day_3_lab.ipynb ├── day_3_lecture.ipynb ├── day_4_assets │ ├── def_sqrt.pkl │ ├── event_tables.zip │ ├── event_tables │ │ ├── bbq_event_1.csv │ │ └── bbq_event_2.csv │ ├── lab │ │ ├── bbq_date_str.pkl │ │ └── output.pkl │ └── recipes │ │ ├── cornbread_recipe.txt │ │ ├── pulled_pork_recipe.txt │ │ └── smoked_mac_and_cheese_recipe.txt ├── day_4_lab.ipynb └── day_4_lecture.ipynb ├── week_4 ├── data │ ├── adult_data.csv │ ├── adult_test.csv │ ├── imdb.csv │ ├── people.csv │ └── weather.csv ├── day_1_lab.ipynb ├── day_1_pandas.ipynb ├── day_2_lab.ipynb ├── day_2_pandas.ipynb ├── day_3_lab.ipynb ├── day_3_visualization.ipynb ├── day_4_lab.ipynb └── day_4_visualization.ipynb └── workshop.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints 2 | .DS_Store 3 | 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Center for Computation and Visualization, Brown University 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Workshop, June 2021 2 | ## Intro 3 | Welcome to 'Introduction to Python Programming and Best Practices'! The goal of this workshop is to increase data fluency of the Brown community. In the first two weeks, we learn Python basics such as variables, container types (e.g., lists and dictionaries), control flow (if statements and for loops), and functions. The third week covers a variety of smaller topics related to the standard Python library, other data formats (like JSON), and how to interact with the operating system via Python. Finally, we will learn how to work with and visualize tabular data (excel, csv, SQL data) using packages like pandas and matplotlib during the last week. 4 | 5 | ## Tools 6 | We provide an yaml file which you can use with conda to recreate the python environemt of the workshop. Please install conda from [here](https://www.anaconda.com/products/individual), and type the following commands into your terminal at the same folder where the workshop material is located: 7 | 8 | *conda env create -n workshop_env -f workshop-python-2021/workshop.yml* 9 | 10 | *conda activate workshop_env* 11 | 12 | Alternatively, you can also use the jupyter hub to run the materials. Click on [http://ccv.jupyter.brown.edu/](http://ccv.jupyter.brown.edu/) and log in with your Brown ID. Once the jupyter-lab starts (it could take a couple of minutes), click on the 'Git Clone' button on the left side and copy the URL of this repo in there. Once the cloning is completed, you should see the week 1-4 folders and the ipython notebooks. 13 | 14 | ## Links to materials 15 | 16 | The table below contains links to the lecture recordings. 17 | 18 | | | lecture | 19 | |------- |:-------: | 20 | | week 1 - day 1 - Introduction | watch video [here](https://drive.google.com/file/d/1yi-Vtj0-gL7AAZGagC4j6e050r1VMavS/view?usp=sharing) | 21 | | week 1 - day 2 - Variables | watch video [here](https://drive.google.com/file/d/1yihexUEK9DlmkxCQhfKmu5cAz0pRzf29/view?usp=sharing) | 22 | | week 1 - day 3 - Lists | watch video [here](https://drive.google.com/file/d/1yj6GdagCOsnj4RpwFDjO8ezwiwnHxTNz/view?usp=sharing) | 23 | | week 1 - day 4 - Dictionaries | watch video [here](https://drive.google.com/file/d/1yorIoUL7qpzcz6-Ui_VLlWA7Kzj89j_L/view?usp=sharing) | 24 | | week 1 - day 5 - If statements | watch video [here](https://drive.google.com/file/d/1ysm1a9YDHTHjM_NjP0yB8nEmKjFyvxVn/view?usp=sharing) | 25 | | week 2 - day 1 - For loops | watch video [here](https://drive.google.com/file/d/1UEi0GhzkJyLagQmRoLVY0ZwejdRtCbdQ/view?usp=sharing) | 26 | | week 2 - day 2 - Combined for loops and if statements | watch video [here](https://drive.google.com/file/d/17bLo5fmKHKXJJx55OIDYql2N49aZMEGK/view?usp=sharing) | 27 | | week 2 - day 3 - Functions | watch video [here](https://drive.google.com/file/d/19rrY5oieylXrY780Hva88D-O9ZX4UPK1/view?usp=sharing) | 28 | | week 2 - day 4 - Code testing | watch video [here](https://drive.google.com/file/d/1kwByOZi6JW-TwV8Ay6wjktgcXkUJ1_q8/view?usp=sharing) | 29 | | week 3 - day 1 - Collections and itertools | watch video [here](https://drive.google.com/file/d/1njKhGgUlHxVRYc-EQbPMyMeMAcivirtk/view?usp=sharing) | 30 | | week 3 - day 2 - Itertools, input/output, reading and writing files | watch video [here](https://drive.google.com/file/d/1mfpCxEAAGkMGW8FtWzuUuHg8q9KDPorK/view?usp=sharing) | 31 | | week 3 - day 3 - System interactions | watch video [here](https://drive.google.com/file/d/1RAxbK46Kv3Am5SRGHHSYWtykghcmSNAe/view?usp=sharing) | 32 | | week 3 - day 4 - Pattern matching, working with datetime variables, and archiving/pickling | watch video [here](https://drive.google.com/file/d/1pfGQkMO9q44Un-amb7slrhXx0H09DRSb/view?usp=sharing) | 33 | | week 4 - day 1 - Pandas | watch video [here](https://drive.google.com/file/d/1z1kr31LaFNzulHiWEtm9wMQ9ORTAXu1y/view?usp=sharing) | 34 | | week 4 - day 2 - Pandas | watch video [here](https://drive.google.com/file/d/1z461KJdvEV4TtZOWVNMNAxnPydx9nLIh/view?usp=sharing) | 35 | | week 4 - day 3 - Visualizations | watch video [here](https://drive.google.com/file/d/1z7s8yMZu_pe5WH0ZLApH1vwBqKMGZuOp/view?usp=sharing) | 36 | | week 4 - day 4 - Visualizations | watch video [here](https://drive.google.com/file/d/1z8RMWlPpWf88aingTAXE7Nc9uWUbLcnz/view?usp=sharing) | 37 | 38 | 39 | 40 | ## Contact 41 | The instructors are Matt Slivinski () and Andras Zsom (). 42 | 43 | ## Acknowledgements 44 | We thank the Data Science Initiative at Brown University for sponsoring the workshop. 45 | -------------------------------------------------------------------------------- /week_1/day_1_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Set up the coding environment\n", 8 | "- we start python coding tomorrow" 9 | ] 10 | } 11 | ], 12 | "metadata": { 13 | "kernelspec": { 14 | "display_name": "Python 3", 15 | "language": "python", 16 | "name": "python3" 17 | }, 18 | "language_info": { 19 | "codemirror_mode": { 20 | "name": "ipython", 21 | "version": 3 22 | }, 23 | "file_extension": ".py", 24 | "mimetype": "text/x-python", 25 | "name": "python", 26 | "nbconvert_exporter": "python", 27 | "pygments_lexer": "ipython3", 28 | "version": "3.8.8" 29 | } 30 | }, 31 | "nbformat": 4, 32 | "nbformat_minor": 4 33 | } 34 | -------------------------------------------------------------------------------- /week_1/day_1_lecture.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "#
Introduction to Python Programming and Best Practices
\n", 12 | "##
Instructors: Matt Slivinski and Andras Zsom
\n", 13 | "###
[Center for Computation and Visualization](https://ccv.brown.edu/)
\n", 14 | "###
Sponsored by the [Data Science Initiative](https://www.brown.edu/initiatives/data-science/home)
" 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "slideshow": { 21 | "slide_type": "slide" 22 | } 23 | }, 24 | "source": [ 25 | "##
Overview of the workshop
\n", 26 | "Learning objectives of the first two weeks:\n", 27 | "- describe and work with container types such as variables, lists, dictionaries, and arrays,\n", 28 | "- describe and write short code snippets using control flow techniques such as if statements, for loops, and list comprehensions,\n", 29 | "- write functions to manipulate data.\n" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": { 35 | "slideshow": { 36 | "slide_type": "subslide" 37 | } 38 | }, 39 | "source": [ 40 | "##
Overview of the workshop
\n", 41 | "Learning objectives of the third week:\n", 42 | "- work with python collections and itertools,\n", 43 | "- manipulate date-time objects,\n", 44 | "- interact with the operating system using os, sys, shutil,\n", 45 | "- parse JSON data with python,\n", 46 | "- parse CSV and SQL data with python.\n" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": { 52 | "slideshow": { 53 | "slide_type": "subslide" 54 | } 55 | }, 56 | "source": [ 57 | "##
Overview of the workshop
\n", 58 | "Learning objectives of the fourth week:\n", 59 | "- use pandas to read in tabular data (CSV, excel, and SQL databases)\n", 60 | "- filter and modify the data\n", 61 | "- visualize the data using pandas and matplotlib\n", 62 | "- calculate summary statistics \n" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "##
What to expect
\n", 70 | "- learning to code is tough but we will do our best to guide you through it\n", 71 | " - always feel free to ask questions! there are no stupid questions, only stupid answers!\n", 72 | " - lots of time to practice and try things yourself\n", 73 | "- you will spend most of your time debugging your code or trying to understand other people's code\n", 74 | " - this can be a very frusrating experince and you will make a lot of mistakes especially in the beginning\n", 75 | " - we will equip you with tools to improve your debugging skills\n", 76 | "- you won't become proficient in python in a month if you start with zero or very little experience\n", 77 | " - but you'll have strong basics to build upon!\n", 78 | "- I hope you'll feel more empowered by the end of the workshop!\n", 79 | " - you'll be able to automate things that would take you way too much time to do manually\n", 80 | " - you will be able to do things with tabular data that you can't do in excel\n", 81 | " - you'll be able to prepare publication-ready figures" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "##
Goal for today: set up and get familiar with your coding environment
\n", 89 | "- download the workshop materials from github\n", 90 | "- install conda\n", 91 | "- create the python environment using conda\n", 92 | "- walk through jupyter-lab" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "### 1. Download the workshop materials\n", 100 | "- go to https://github.com/brown-ccv/workshop-python-2021\n", 101 | "- click on 'Code'\n", 102 | "- download zip\n", 103 | "- unzip the file whereever you'd like the workshop material to be (maybe the Documents folder?)\n", 104 | "\n", 105 | "If you are familiar with git, simply clone the repo. Type in the terminal:\n", 106 | "\n", 107 | "*git clone https://github.com/brown-ccv/workshop-python-2021.git*\n" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "metadata": {}, 113 | "source": [ 114 | "## 2. Install conda\n", 115 | "- https://www.anaconda.com/products/individual" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "metadata": {}, 121 | "source": [ 122 | "## 3. Create the python environment\n", 123 | "- python and the packages we will use change over time\n", 124 | "- we will show you how to create a reproducable python environment\n", 125 | "- you can recreate this environment on any machine years down the road and you'll be able to run the notebooks of the workshop\n", 126 | "\n", 127 | "- open a terminal/console/command line tool\n", 128 | "- make sure you are in the same folder where the material is\n", 129 | " - if you type *ls* or *dir*, you should see the folder *workshop-python-2021*\n", 130 | "- type the following commands in the terminal\n", 131 | "\n", 132 | "*conda env create -n workshop_env -f workshop-python-2021/workshop.yml*\n", 133 | "\n", 134 | "*conda activate workshop_env*\n", 135 | "\n", 136 | "- then you can type *jupyter-lab* and the jupyter lab window should open up in your browser" 137 | ] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "## 4. Jupyter lab walk through" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "metadata": {}, 149 | "source": [ 150 | "## Plan B\n", 151 | "If the installation is unsuccessful, you can also use the jupyter hub:\n", 152 | "\n", 153 | "http://ccv.jupyter.brown.edu/\n", 154 | "\n", 155 | "This is not our default method during the workshop because the hub is a cloud-based service, it might be temporary, it's not easy to change the coding environment if you need to. \n" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 1, 161 | "metadata": {}, 162 | "outputs": [], 163 | "source": [ 164 | "import pandas as pd\n", 165 | "\n" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 2, 171 | "metadata": {}, 172 | "outputs": [ 173 | { 174 | "name": "stdout", 175 | "output_type": "stream", 176 | "text": [ 177 | "hello\n" 178 | ] 179 | } 180 | ], 181 | "source": [ 182 | "print('hello')" 183 | ] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "metadata": {}, 188 | "source": [ 189 | "# Introductions\n", 190 | "Hello, my name is Andras.\n", 191 | "\n", 192 | "**this text is bold**" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [] 201 | } 202 | ], 203 | "metadata": { 204 | "celltoolbar": "Slideshow", 205 | "kernelspec": { 206 | "display_name": "Python 3", 207 | "language": "python", 208 | "name": "python3" 209 | }, 210 | "language_info": { 211 | "codemirror_mode": { 212 | "name": "ipython", 213 | "version": 3 214 | }, 215 | "file_extension": ".py", 216 | "mimetype": "text/x-python", 217 | "name": "python", 218 | "nbconvert_exporter": "python", 219 | "pygments_lexer": "ipython3", 220 | "version": "3.8.8" 221 | } 222 | }, 223 | "nbformat": 4, 224 | "nbformat_minor": 4 225 | } 226 | -------------------------------------------------------------------------------- /week_1/day_2_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# P1: create variables using the hungarian notation\n", 8 | "The value of pi is 3.1416. Create a variable and store this value." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "pi_flt = 3.1416\n" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "There are 86400 seconds in a day. What variable type is suitable to store this value? The variable name should start with `seconds_in_day_`." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 2, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "seconds_in_day_int = 86400" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "# P2: Are the following variables named correctly? \n", 41 | "\n", 42 | "Create a new boolean variable that checks if their type is correctly indicated in the variable name. The name of the boolean variable should start with the same string as the original variable. For example, if the variable is `a_int`, the boolean variabe should be `a_bool`; or if the variable is `num_flt`, the boolean variable should be `num_bool`." 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 3, 48 | "metadata": {}, 49 | "outputs": [ 50 | { 51 | "name": "stdout", 52 | "output_type": "stream", 53 | "text": [ 54 | "True\n" 55 | ] 56 | } 57 | ], 58 | "source": [ 59 | "somenum_int = 623\n", 60 | "\n", 61 | "somenum_bool = type(somenum_int) == int\n", 62 | "\n", 63 | "print(somenum_bool)\n", 64 | "\n", 65 | "# True" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 4, 71 | "metadata": {}, 72 | "outputs": [ 73 | { 74 | "name": "stdout", 75 | "output_type": "stream", 76 | "text": [ 77 | "False\n" 78 | ] 79 | } 80 | ], 81 | "source": [ 82 | "someothernum_flt = 92\n", 83 | "\n", 84 | "someothernum_bool = type(someothernum_flt) == float\n", 85 | "\n", 86 | "print(someothernum_bool)\n", 87 | "# False" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 3, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "whatevs_flt = 456.256\n", 97 | "\n", 98 | "\n", 99 | "# True" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 4, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "giraffe_int = 78.13\n", 109 | "\n", 110 | "\n", 111 | "# False" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "# P3: Update an existing variable or create a new one using hungarian notation as appropriate." 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": 7, 124 | "metadata": {}, 125 | "outputs": [ 126 | { 127 | "name": "stdout", 128 | "output_type": "stream", 129 | "text": [ 130 | "654.0\n" 131 | ] 132 | } 133 | ], 134 | "source": [ 135 | "# Multiply the variable below by 2. Can you use the same variable to store the new value?\n", 136 | "# Or do you need to create a new one?\n", 137 | "somenum_int = 327\n", 138 | "\n", 139 | "print(somenum_int*2.0)\n", 140 | "somenum_flt = somenum_int * 2.0\n", 141 | "#somenum_int = somenum_int*2\n", 142 | "\n", 143 | "# no" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": 9, 149 | "metadata": {}, 150 | "outputs": [ 151 | { 152 | "name": "stdout", 153 | "output_type": "stream", 154 | "text": [ 155 | "\n" 156 | ] 157 | } 158 | ], 159 | "source": [ 160 | "# Multiply the variable below by 2.25. Can you use the same variable to store the new value?\n", 161 | "# Or do you need to create a new one?\n", 162 | "someothernum_int = 67\n", 163 | "print(type(someothernum_int*2.25))\n", 164 | "someothernum_flt = someothernum_int*2.25\n", 165 | "# yes" 166 | ] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "metadata": {}, 171 | "source": [ 172 | "# P4: string indexing" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "For all exercises in Problem 4, print the result. \n", 180 | "\n", 181 | "Define a string variable called `sentence_str` where the value is a sentence: \n", 182 | "`All dogs are good and cool.`" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 11, 188 | "metadata": {}, 189 | "outputs": [ 190 | { 191 | "name": "stdout", 192 | "output_type": "stream", 193 | "text": [ 194 | "All dogs are good and cool.\n" 195 | ] 196 | } 197 | ], 198 | "source": [ 199 | "sentence_str = 'All dogs are good and cool.'\n", 200 | "print(sentence_str)" 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "Assign the last 4 letters of the string to a variable, `a_str`" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 12, 213 | "metadata": {}, 214 | "outputs": [ 215 | { 216 | "name": "stdout", 217 | "output_type": "stream", 218 | "text": [ 219 | "ool.\n" 220 | ] 221 | } 222 | ], 223 | "source": [ 224 | "a_str = sentence_str[-4:]\n", 225 | "print(a_str)\n" 226 | ] 227 | }, 228 | { 229 | "cell_type": "markdown", 230 | "metadata": {}, 231 | "source": [ 232 | "Assign the string backwards to a variable, `b_str`" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 14, 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "\n", 242 | "b_str = sentence_str[::-1]" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "Assign the first and last 2 letters of the string to a variable, `c_str`" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 16, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "All.\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "\n", 267 | "c_str = sentence_str[:2] + sentence_str[-2:]\n", 268 | "\n", 269 | "print(c_str)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "metadata": {}, 275 | "source": [ 276 | "Repeat the string 3 times and assign to a variable, `d_str`" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 17, 282 | "metadata": {}, 283 | "outputs": [ 284 | { 285 | "name": "stdout", 286 | "output_type": "stream", 287 | "text": [ 288 | "All dogs are good and cool.All dogs are good and cool.All dogs are good and cool.\n" 289 | ] 290 | } 291 | ], 292 | "source": [ 293 | "d_str = sentence_str*3\n", 294 | "print(d_str)\n" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "metadata": {}, 300 | "source": [ 301 | "Assign the string concatenated with the word \"sometimes\" to a variable, `e_str`" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 18, 307 | "metadata": {}, 308 | "outputs": [ 309 | { 310 | "name": "stdout", 311 | "output_type": "stream", 312 | "text": [ 313 | "All dogs are good and cool sometimes.\n" 314 | ] 315 | } 316 | ], 317 | "source": [ 318 | "e_str = sentence_str[:-1] + ' ' + 'sometimes.'\n", 319 | "\n", 320 | "print(e_str)\n" 321 | ] 322 | }, 323 | { 324 | "cell_type": "markdown", 325 | "metadata": {}, 326 | "source": [ 327 | "Split the string into words and assign to a variable, `f_str`" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 19, 333 | "metadata": {}, 334 | "outputs": [ 335 | { 336 | "name": "stdout", 337 | "output_type": "stream", 338 | "text": [ 339 | "['All', 'dogs', 'are', 'good', 'and', 'cool.']\n" 340 | ] 341 | } 342 | ], 343 | "source": [ 344 | "f_str = sentence_str.split()\n", 345 | "\n", 346 | "print(f_str)" 347 | ] 348 | }, 349 | { 350 | "cell_type": "markdown", 351 | "metadata": {}, 352 | "source": [ 353 | "# P5 - string operations " 354 | ] 355 | }, 356 | { 357 | "cell_type": "markdown", 358 | "metadata": {}, 359 | "source": [ 360 | "Using the following building blocks, create a string that says `The dog said, \"woof woof woof\" and the cat answered, \"hisshiss\".` Assign to a variable, `catdog_str`. Print the variable.\n", 361 | "\n", 362 | "```dog_string = 'The dog said'\n", 363 | "woof_string = 'woof'\n", 364 | "cat_string = 'and the cat answered'\n", 365 | "hiss_string = 'hiss'```" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 21, 371 | "metadata": {}, 372 | "outputs": [ 373 | { 374 | "name": "stdout", 375 | "output_type": "stream", 376 | "text": [ 377 | "The dog said \"woofwoofwoof\" and the cat answered \"hisshiss\".\n" 378 | ] 379 | } 380 | ], 381 | "source": [ 382 | "dog_string = 'The dog said'\n", 383 | "woof_string = 'woof'\n", 384 | "cat_string = 'and the cat answered'\n", 385 | "hiss_string = 'hiss'\n", 386 | "\n", 387 | "catdog_str = dog_string + ' \"' + woof_string*3 + '\" ' + cat_string + ' \"' + hiss_string * 2 + '\".'\n", 388 | "\n", 389 | "print(catdog_str)\n" 390 | ] 391 | }, 392 | { 393 | "cell_type": "markdown", 394 | "metadata": {}, 395 | "source": [ 396 | "# P6: Bonus" 397 | ] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "metadata": {}, 402 | "source": [ 403 | "Bonus: look up Python string functions and lowercase all the letters in `sentence_str` using a single function. Assign the result to a variable called `lower_str` and print." 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 22, 409 | "metadata": {}, 410 | "outputs": [ 411 | { 412 | "name": "stdout", 413 | "output_type": "stream", 414 | "text": [ 415 | "all dogs are good and cool.\n" 416 | ] 417 | } 418 | ], 419 | "source": [ 420 | "lower_str = sentence_str.lower()\n", 421 | "\n", 422 | "print(lower_str)\n" 423 | ] 424 | }, 425 | { 426 | "cell_type": "markdown", 427 | "metadata": {}, 428 | "source": [ 429 | "# P7: Bonus " 430 | ] 431 | }, 432 | { 433 | "cell_type": "markdown", 434 | "metadata": {}, 435 | "source": [ 436 | "Bonus: look up Python string functions and find out whether the word \"are\" appears in your sentence. If it does, assign the first index where the word appears to a variable, `index_int`, and print." 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": 25, 442 | "metadata": {}, 443 | "outputs": [ 444 | { 445 | "name": "stdout", 446 | "output_type": "stream", 447 | "text": [ 448 | "True\n", 449 | "9\n", 450 | "are good and cool.\n" 451 | ] 452 | } 453 | ], 454 | "source": [ 455 | "print('are' in sentence_str)\n", 456 | "index_int = sentence_str.find('are')\n", 457 | "print(index_int)\n", 458 | "print(sentence_str[9:])\n" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "metadata": {}, 465 | "outputs": [], 466 | "source": [] 467 | } 468 | ], 469 | "metadata": { 470 | "kernelspec": { 471 | "display_name": "Python 3", 472 | "language": "python", 473 | "name": "python3" 474 | }, 475 | "language_info": { 476 | "codemirror_mode": { 477 | "name": "ipython", 478 | "version": 3 479 | }, 480 | "file_extension": ".py", 481 | "mimetype": "text/x-python", 482 | "name": "python", 483 | "nbconvert_exporter": "python", 484 | "pygments_lexer": "ipython3", 485 | "version": "3.8.8" 486 | } 487 | }, 488 | "nbformat": 4, 489 | "nbformat_minor": 4 490 | } 491 | -------------------------------------------------------------------------------- /week_1/day_3_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## P1: Create a list of your favorite things!\n", 8 | "\n", 9 | "The container name should be `my_favorite_things_lst` and the elements should be strings. Please add at least 3 elements." 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 21, 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "['chocolate', 'wine', 'oranges']\n" 22 | ] 23 | } 24 | ], 25 | "source": [ 26 | "my_favorite_things_lst = ['chocolate', 'wine', 'oranges']\n", 27 | "\n", 28 | "print(my_favorite_things_lst)" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "## P2: Update the list, insert and remove elements.\n", 36 | "Go through the following steps and update your list." 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "P2a: my favorite thing is my dog, Waiola. Please add her name as the last element of the list." 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 22, 49 | "metadata": {}, 50 | "outputs": [ 51 | { 52 | "name": "stdout", 53 | "output_type": "stream", 54 | "text": [ 55 | "['chocolate', 'wine', 'oranges', 'waiola']\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "my_favorite_things_lst.append('waiola')\n", 61 | "\n", 62 | "print(my_favorite_things_lst)" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": {}, 68 | "source": [ 69 | "P2b: Matt's favorite thing is his dog, Kelly. Please insert his name to be the second element of the list. " 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 23, 75 | "metadata": {}, 76 | "outputs": [ 77 | { 78 | "name": "stdout", 79 | "output_type": "stream", 80 | "text": [ 81 | "['chocolate', 'wine', 'oranges', 'waiola', 'Callie']\n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "my_favorite_things_lst.append('Callie')\n", 87 | "\n", 88 | "print(my_favorite_things_lst)" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "P2c: Please update the third element of the list to be chocolate. :)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 24, 101 | "metadata": {}, 102 | "outputs": [ 103 | { 104 | "name": "stdout", 105 | "output_type": "stream", 106 | "text": [ 107 | "['chocolate', 'wine', 'chocolate', 'waiola', 'Callie']\n" 108 | ] 109 | } 110 | ], 111 | "source": [ 112 | "my_favorite_things_lst[2] = 'chocolate'\n", 113 | "\n", 114 | "print(my_favorite_things_lst)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "P2d: Please delete the first element of the list. " 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": 25, 127 | "metadata": {}, 128 | "outputs": [ 129 | { 130 | "name": "stdout", 131 | "output_type": "stream", 132 | "text": [ 133 | "['wine', 'chocolate', 'waiola', 'Callie']\n" 134 | ] 135 | } 136 | ], 137 | "source": [ 138 | "del my_favorite_things_lst[0]\n", 139 | "\n", 140 | "print(my_favorite_things_lst)" 141 | ] 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "metadata": {}, 146 | "source": [ 147 | "## P3: List slicing" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 10, 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "some_nums_lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]" 157 | ] 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "metadata": {}, 162 | "source": [ 163 | "P3a: create a new list called sub_lst that contains every third element of `some_nums_lst`." 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 26, 169 | "metadata": {}, 170 | "outputs": [ 171 | { 172 | "name": "stdout", 173 | "output_type": "stream", 174 | "text": [ 175 | "[1, 4, 7, 10, 13, 16]\n" 176 | ] 177 | } 178 | ], 179 | "source": [ 180 | "sub_lst = some_nums_lst[::3]\n", 181 | "print(sub_lst)\n", 182 | "# [1, 4, 7, 10, 13, 16]" 183 | ] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "metadata": {}, 188 | "source": [ 189 | "P3b: Now sub_lst should be every second element in reversed order." 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 27, 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "name": "stdout", 199 | "output_type": "stream", 200 | "text": [ 201 | "[16, 14, 12, 10, 8, 6, 4, 2]\n" 202 | ] 203 | } 204 | ], 205 | "source": [ 206 | "sub_lst = some_nums_lst[::-2]\n", 207 | "print(sub_lst)\n", 208 | "# [16, 14, 12, 10, 8, 6, 4, 2]" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "P3c: Now sub_lst should be every 4th element starting from the third element of `some_nums_lst`." 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": 28, 221 | "metadata": {}, 222 | "outputs": [ 223 | { 224 | "name": "stdout", 225 | "output_type": "stream", 226 | "text": [ 227 | "[3, 7, 11, 15]\n" 228 | ] 229 | } 230 | ], 231 | "source": [ 232 | "sub_lst = some_nums_lst[2::4]\n", 233 | "print(sub_lst)\n", 234 | "\n", 235 | "# [3, 7, 11, 15]" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "## P4: Lists of lists" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "P4a: create an empty list named `nested_lst`. The first element of this list should be `my_favorite_things_lst`, the second element should be `some_nums_lst`, the third element should be a list that contains two strings: your first and last names." 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 30, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "name": "stdout", 259 | "output_type": "stream", 260 | "text": [ 261 | "3\n", 262 | "[['wine', 'chocolate', 'waiola', 'Callie'], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], ['Andras', 'Zsom']]\n" 263 | ] 264 | } 265 | ], 266 | "source": [ 267 | "nested_lst = []\n", 268 | "\n", 269 | "nested_lst.append(my_favorite_things_lst)\n", 270 | "nested_lst.append(some_nums_lst)\n", 271 | "nested_lst.append(['Andras', 'Zsom'])\n", 272 | "\n", 273 | "#nested_lst = [my_favorite_things_lst, some_nums_lst, ['Andras', 'Zsom']]\n", 274 | "\n", 275 | "print(len(nested_lst))\n", 276 | "\n", 277 | "print(nested_lst)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "P4b: Save the fifth element of the second list to the variable called `var1_` with the ending that properly describes the variable type." 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 31, 290 | "metadata": {}, 291 | "outputs": [ 292 | { 293 | "name": "stdout", 294 | "output_type": "stream", 295 | "text": [ 296 | "5\n" 297 | ] 298 | } 299 | ], 300 | "source": [ 301 | "var1_int = nested_lst[1][4]\n", 302 | "\n", 303 | "print(var1_int)\n", 304 | "\n", 305 | "# 5" 306 | ] 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "metadata": {}, 311 | "source": [ 312 | "P4c: Create a `first_name_str` variable and assign your first name from `nested_lst` to it." 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 32, 318 | "metadata": {}, 319 | "outputs": [ 320 | { 321 | "name": "stdout", 322 | "output_type": "stream", 323 | "text": [ 324 | "Andras\n" 325 | ] 326 | } 327 | ], 328 | "source": [ 329 | "first_name_str = nested_lst[2][0]\n", 330 | "print(first_name_str)\n" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": null, 336 | "metadata": {}, 337 | "outputs": [], 338 | "source": [] 339 | } 340 | ], 341 | "metadata": { 342 | "kernelspec": { 343 | "display_name": "Python 3", 344 | "language": "python", 345 | "name": "python3" 346 | }, 347 | "language_info": { 348 | "codemirror_mode": { 349 | "name": "ipython", 350 | "version": 3 351 | }, 352 | "file_extension": ".py", 353 | "mimetype": "text/x-python", 354 | "name": "python", 355 | "nbconvert_exporter": "python", 356 | "pygments_lexer": "ipython3", 357 | "version": "3.8.8" 358 | } 359 | }, 360 | "nbformat": 4, 361 | "nbformat_minor": 4 362 | } 363 | -------------------------------------------------------------------------------- /week_1/day_4_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
Problem 1
" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "You are working in a CVS store and you were asked to make an inventory. The following items are in the store: \n", 15 | "\n", 16 | "chocolate bars, shampoo, hand sanitizer, toilet paper, dog treats, aspirin\n", 17 | "\n", 18 | "Here are the counts of the various items:\n", 19 | "\n", 20 | "8, 3, 5, 0, 10, 2\n", 21 | "\n", 22 | "Create a dictionary which describes how many items there are of each product at the store." 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": null, 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "#
Problem 2
" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "A shopper came to the store and bought 2 chocolate bars, 1 hand sanitizer, and aspirin. Please update the dictionary.\n", 44 | "\n", 45 | "The store was restocked at the end of the day. You received 10 toilet papers, 3 listerines, 5 aspirings, and 8 hand sanitizers. \n", 46 | "\n", 47 | "What's the inventory at the end of the day?" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": null, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "#
Problem 3
" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "There is a second store in town with the following inventory:\n", 69 | "\n", 70 | "4 shower gels, 2 toilet papers, 4 dog treats, 8 hand sanitizers, 5 chocolate bars, 3 cereals.\n", 71 | "\n", 72 | "Create a dictionary for this second store.\n", 73 | "\n", 74 | "Your task is to create a dictionary that shows the combined inventory of the two stores." 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [] 83 | } 84 | ], 85 | "metadata": { 86 | "kernelspec": { 87 | "display_name": "Python 3", 88 | "language": "python", 89 | "name": "python3" 90 | }, 91 | "language_info": { 92 | "codemirror_mode": { 93 | "name": "ipython", 94 | "version": 3 95 | }, 96 | "file_extension": ".py", 97 | "mimetype": "text/x-python", 98 | "name": "python", 99 | "nbconvert_exporter": "python", 100 | "pygments_lexer": "ipython3", 101 | "version": "3.8.8" 102 | } 103 | }, 104 | "nbformat": 4, 105 | "nbformat_minor": 4 106 | } 107 | -------------------------------------------------------------------------------- /week_1/day_5_if_statements.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Control flow - the 'grammar' of programing languages\n", 12 | "Today we cover if statements, next you'll learn about for loops\n", 13 | "\n", 14 | "### By the end of the day you'll be able to\n", 15 | "- create simple if statements\n", 16 | "- create if statements with multiple conditions\n", 17 | "- create a sequence of if-else statements" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": { 23 | "slideshow": { 24 | "slide_type": "slide" 25 | } 26 | }, 27 | "source": [ 28 | "#
Control flow
\n", 29 | "### Every code can be broken down to pieces like this:\n", 30 | "- **Instructions**: \"Do this; then do that.\"\n", 31 | "- **If statements**: \"If the condition is true, perform this action; otherwise, do that action.\"\n", 32 | "- **For loops**: \"Do this action that number of times.\"\n", 33 | "- **While loops**: \"Keep doing that until this condition is false.\"\n", 34 | "\n", 35 | "**The instructions operate on variables and containers.**\n", 36 | "\n", 37 | "### Programming is like playing with lego. " 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": { 43 | "slideshow": { 44 | "slide_type": "slide" 45 | } 46 | }, 47 | "source": [ 48 | "### By the end of the day you'll be able to\n", 49 | "- **create simple if statements**\n", 50 | "- create if statements with multiple conditions\n", 51 | "- create a sequence of if-else statements" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 1, 57 | "metadata": {}, 58 | "outputs": [ 59 | { 60 | "ename": "IndentationError", 61 | "evalue": "expected an indented block (, line 4)", 62 | "output_type": "error", 63 | "traceback": [ 64 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m else:\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" 65 | ] 66 | } 67 | ], 68 | "source": [ 69 | "if condition(s): # stuff after the if is a boolean variable (either true or false)\n", 70 | " # do something\n", 71 | " # you must indent \n", 72 | "else:\n", 73 | " # do something else\n", 74 | " # you must indent this as well\n", 75 | "# instructions \n" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 11, 81 | "metadata": { 82 | "slideshow": { 83 | "slide_type": "subslide" 84 | } 85 | }, 86 | "outputs": [ 87 | { 88 | "name": "stdout", 89 | "output_type": "stream", 90 | "text": [ 91 | "can vote\n" 92 | ] 93 | } 94 | ], 95 | "source": [ 96 | "age_int = 100 # instruction: assign the integer value 18 to age_int\n", 97 | "\n", 98 | "if age_int > 17: # note that the condition is a boolean variable with a value true or false\n", 99 | " print(\"can vote\") # what we print is a string variable\n", 100 | "else:\n", 101 | " print(\"cannot vote\") # another string variable" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 12, 107 | "metadata": { 108 | "slideshow": { 109 | "slide_type": "subslide" 110 | } 111 | }, 112 | "outputs": [ 113 | { 114 | "name": "stdout", 115 | "output_type": "stream", 116 | "text": [ 117 | "cannot vote\n" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "# four instructions: assign values to variables\n", 123 | "age_int = 17\n", 124 | "check_age_bool = age_int > 17\n", 125 | "var1_str = 'can vote'\n", 126 | "var2_str = 'cannot vote'\n", 127 | "\n", 128 | "# if-else statement\n", 129 | "if check_age_bool: \n", 130 | " print(var1_str)\n", 131 | "else:\n", 132 | " print(var2_str)\n", 133 | " " 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": 15, 139 | "metadata": { 140 | "slideshow": { 141 | "slide_type": "subslide" 142 | } 143 | }, 144 | "outputs": [ 145 | { 146 | "name": "stdout", 147 | "output_type": "stream", 148 | "text": [ 149 | "False\n", 150 | "this is outside of the if statement\n" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "# you can also change a variable's value in an if statement\n", 156 | "\n", 157 | "age_int = 17\n", 158 | "\n", 159 | "if age_int > 17: \n", 160 | " can_vote_bool = True\n", 161 | "else:\n", 162 | " can_vote_bool = False\n", 163 | "\n", 164 | "print(can_vote_bool)\n", 165 | "print('this is outside of the if statement')" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 17, 171 | "metadata": { 172 | "slideshow": { 173 | "slide_type": "subslide" 174 | } 175 | }, 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "no\n" 182 | ] 183 | } 184 | ], 185 | "source": [ 186 | "# condition/boolean variable can check type, list length, anything really\n", 187 | "# and you can do anything inside the if and else parts too\n", 188 | "age_int = 99.0\n", 189 | "\n", 190 | "if type(age_int) == int:\n", 191 | " variable_named_correctly_str = 'yes'\n", 192 | "else:\n", 193 | " variable_named_correctly_str = 'no'\n", 194 | " \n", 195 | "print(variable_named_correctly_str)" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": { 201 | "slideshow": { 202 | "slide_type": "slide" 203 | } 204 | }, 205 | "source": [ 206 | "## Exercise 1\n", 207 | "Check if the list below has at least 10 elements. If it does, append the string 'yes' to the list. If it does not, append the string 'no' to the list. Test your code by adding elements to my_lst so you explore both conditions (less than or at least 10 elements)." 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 23, 213 | "metadata": {}, 214 | "outputs": [ 215 | { 216 | "name": "stdout", 217 | "output_type": "stream", 218 | "text": [ 219 | "[1, 67, 'whatever', 'etc', 234, True, 'a', 'b', 'c', 'd', 'no']\n" 220 | ] 221 | } 222 | ], 223 | "source": [ 224 | "my_lst = [1, 67, 'whatever', 'etc', 234 , True, 'a','b','c','d']\n", 225 | "\n", 226 | "# add your code here\n", 227 | "if len(my_lst) >= 10:\n", 228 | " my_lst.append('yes')\n", 229 | "else:\n", 230 | " my_lst.append('no')\n", 231 | " \n", 232 | "print(my_lst)\n", 233 | "\n", 234 | "\n" 235 | ] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "metadata": { 240 | "slideshow": { 241 | "slide_type": "slide" 242 | } 243 | }, 244 | "source": [ 245 | "### By the end of the day you'll be able to\n", 246 | "- create simple if statements\n", 247 | "- **create if statements with multiple conditions**\n", 248 | "- create a sequence of if-else statements" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 29, 254 | "metadata": { 255 | "slideshow": { 256 | "slide_type": "-" 257 | } 258 | }, 259 | "outputs": [ 260 | { 261 | "name": "stdout", 262 | "output_type": "stream", 263 | "text": [ 264 | "cannot walk\n", 265 | "True\n", 266 | "False\n", 267 | "False\n", 268 | "False\n" 269 | ] 270 | } 271 | ], 272 | "source": [ 273 | "# multiple conditions with *and*\n", 274 | "# all conditions need to be True\n", 275 | "\n", 276 | "age_int = 101\n", 277 | "\n", 278 | "#print((age_int >= 2))\n", 279 | "#print((age_int <= 100))\n", 280 | "#print((age_int >= 2) and (age_int <= 100))\n", 281 | "\n", 282 | "if (age_int >= 2) and (age_int <= 100): # multiple conditions need to be in parentheses, these are boolean variables \n", 283 | " print(\"can walk\") # print a string\n", 284 | "else:\n", 285 | " print(\"cannot walk\") # print another string\n", 286 | " \n", 287 | "print(True and True)\n", 288 | "print(True and False)\n", 289 | "print(False and True)\n", 290 | "print(False and False)\n", 291 | " \n", 292 | " " 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": 38, 298 | "metadata": { 299 | "slideshow": { 300 | "slide_type": "subslide" 301 | } 302 | }, 303 | "outputs": [ 304 | { 305 | "name": "stdout", 306 | "output_type": "stream", 307 | "text": [ 308 | "cannot walk\n", 309 | "False\n" 310 | ] 311 | } 312 | ], 313 | "source": [ 314 | "# multiple conditions with *or*\n", 315 | "# it is enough if one condition is True\n", 316 | "\n", 317 | "age_int = 1\n", 318 | "\n", 319 | "if (age_int < 2) or (age_int > 100): # multiple conditions need to be in parentheses, these are boolean variables \n", 320 | " print(\"cannot walk\") # print a string\n", 321 | "else:\n", 322 | " print(\"can walk\") # print another string\n", 323 | " \n", 324 | " \n", 325 | "#print(True or True)\n", 326 | "#print(True or False)\n", 327 | "#print(False or True)\n", 328 | "#print(False or False)\n", 329 | "\n", 330 | "print(not age_int > 2)\n" 331 | ] 332 | }, 333 | { 334 | "cell_type": "markdown", 335 | "metadata": { 336 | "slideshow": { 337 | "slide_type": "slide" 338 | } 339 | }, 340 | "source": [ 341 | "## Exercise 2\n", 342 | "Check if a string contains the vowels 'a' or 'e'. Create a variable called has_a_e_bool and set its value appropriately. Please change the value of the string such that you try words with 'a' and 'e', only an 'a', only 'e', and no 'a' or 'e'. This way you explore all options and test your code." 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 42, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "name": "stdout", 352 | "output_type": "stream", 353 | "text": [ 354 | "True\n" 355 | ] 356 | } 357 | ], 358 | "source": [ 359 | "my_str = 'apple'\n", 360 | "\n", 361 | "if ('a' in my_str) or ('e' in my_str):\n", 362 | " has_a_e_bool = True\n", 363 | "else:\n", 364 | " has_a_e_bool = False\n", 365 | "\n", 366 | "print(has_a_e_bool)" 367 | ] 368 | }, 369 | { 370 | "cell_type": "markdown", 371 | "metadata": { 372 | "slideshow": { 373 | "slide_type": "slide" 374 | } 375 | }, 376 | "source": [ 377 | "### By the end of the day you'll be able to\n", 378 | "- create simple if statements\n", 379 | "- create if statements with multiple conditions\n", 380 | "- **create a sequence of if-else statements**" 381 | ] 382 | }, 383 | { 384 | "cell_type": "code", 385 | "execution_count": 50, 386 | "metadata": {}, 387 | "outputs": [ 388 | { 389 | "name": "stdout", 390 | "output_type": "stream", 391 | "text": [ 392 | "not US coin\n" 393 | ] 394 | } 395 | ], 396 | "source": [ 397 | "cents_int = 100\n", 398 | "\n", 399 | "if cents_int == 25:\n", 400 | " print(\"washington\")\n", 401 | "elif cents_int == 10:\n", 402 | " print(\"roosevelt\")\n", 403 | "elif cents_int == 5:\n", 404 | " print(\"jefferson\")\n", 405 | "elif cents_int == 1:\n", 406 | " print(\"lincoln\")\n", 407 | "else:\n", 408 | " print(\"not US coin\")" 409 | ] 410 | }, 411 | { 412 | "cell_type": "markdown", 413 | "metadata": { 414 | "slideshow": { 415 | "slide_type": "slide" 416 | } 417 | }, 418 | "source": [ 419 | "## Exercise 3\n", 420 | "Let's compare two numbers x_int and y_int. Check if x_int is larger than y_int, else if x_int is equal to y_int, or else if x_int is smaller than y_int. Create a string called compare_str and set its value to either 'larger', 'equal', or 'smaller' as appropriate. Test your code by changing the values of x_int and y_int so you explore all three conditions!" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": 56, 426 | "metadata": {}, 427 | "outputs": [ 428 | { 429 | "name": "stdout", 430 | "output_type": "stream", 431 | "text": [ 432 | "larger\n" 433 | ] 434 | } 435 | ], 436 | "source": [ 437 | "x_int = 10\n", 438 | "y_int = 8\n", 439 | "\n", 440 | "if x_int > y_int:\n", 441 | " print('larger')\n", 442 | "elif x_int == y_int:\n", 443 | " print('equal')\n", 444 | "else:\n", 445 | " print('smaller')\n", 446 | "\n" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": null, 452 | "metadata": {}, 453 | "outputs": [], 454 | "source": [] 455 | }, 456 | { 457 | "cell_type": "code", 458 | "execution_count": null, 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [] 462 | } 463 | ], 464 | "metadata": { 465 | "celltoolbar": "Slideshow", 466 | "kernelspec": { 467 | "display_name": "Python 3", 468 | "language": "python", 469 | "name": "python3" 470 | }, 471 | "language_info": { 472 | "codemirror_mode": { 473 | "name": "ipython", 474 | "version": 3 475 | }, 476 | "file_extension": ".py", 477 | "mimetype": "text/x-python", 478 | "name": "python", 479 | "nbconvert_exporter": "python", 480 | "pygments_lexer": "ipython3", 481 | "version": "3.8.8" 482 | } 483 | }, 484 | "nbformat": 4, 485 | "nbformat_minor": 4 486 | } 487 | -------------------------------------------------------------------------------- /week_1/day_5_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Exercise 1\n", 8 | "If the weight of your luggage is larger than 50 lbs, you need to pay an extra charge. Create a boolean variable `pay_charge_bool` and make it true if a charge needs to be paid, false otherwise. Please test your code by trying weights less than, equal to, and larger than 50 lbs." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "weight_flt = 55.3\n", 18 | "\n" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## Exercise 2\n", 26 | "A roller coaster is only open to kids between ages of 8 and 12. Create a can_enter_bool variable and set it to true if a person can enter, false otherwise. Don't forget to try all possibilities!" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 2, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "age_int = 6\n", 36 | "\n" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "## Exercise 3\n", 44 | "\n", 45 | "Work based on the cents if statement we discussed during the class and rewrite it such that it saves who is on the US dollar notes into face_str. Start by creating a variable called dollar_int. Washington is on the 1, Jefferson is on the 2, Lincoln is on the 5, Hamilton is on the 10, Jackson is on the 20, Grant is on the 50, and finally Franklin is on the 100. Also consider the case when dollar_int is not 1, 2, 5, 10, 20, 50, or 100. Then face_str should be `not on US banknote`." 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 3, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "notes_int = 1\n", 55 | "\n" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [] 64 | } 65 | ], 66 | "metadata": { 67 | "kernelspec": { 68 | "display_name": "Python 3", 69 | "language": "python", 70 | "name": "python3" 71 | }, 72 | "language_info": { 73 | "codemirror_mode": { 74 | "name": "ipython", 75 | "version": 3 76 | }, 77 | "file_extension": ".py", 78 | "mimetype": "text/x-python", 79 | "name": "python", 80 | "nbconvert_exporter": "python", 81 | "pygments_lexer": "ipython3", 82 | "version": "3.8.8" 83 | } 84 | }, 85 | "nbformat": 4, 86 | "nbformat_minor": 4 87 | } 88 | -------------------------------------------------------------------------------- /week_2/data/Bubble-sort-example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_2/data/Bubble-sort-example.gif -------------------------------------------------------------------------------- /week_2/data/panda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_2/data/panda.jpg -------------------------------------------------------------------------------- /week_2/day_1_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "### ** Exercise**\n", 12 | "\n", 13 | "Using `name_str`, loop through the letters in the string, printing each letter" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "name_str = 'Willie'" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": null, 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "# TODO: insert solution here" 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "### ** Exercise**\n", 39 | "\n", 40 | "Loop through the letters in `name_str`, printing each element uppercased using the `.upper()` method" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# TODO: insert solution here" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "### ** Exercise**\n", 57 | "\n", 58 | "Loop through the letters in the string, add a space and a period to each element and print each element\n", 59 | "\n", 60 | "Use the format:\n", 61 | "```python\n", 62 | "for letter in name_str:\n", 63 | " new_letter = ...\n", 64 | "```" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "# TODO: insert solution here" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "### ** Exercise**\n", 81 | "\n", 82 | "Loop through the letters in `name_str`, concatenating each element to `sentence_str`, and print `sentence_str`." 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "sentence_str = 'My name is: '" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "# TODO: insert solution here" 101 | ] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "metadata": {}, 106 | "source": [ 107 | "### ** Exercise**\n", 108 | "\n", 109 | "Create a list called `word_list` containing the words \"Willie\", \"likes\", \"sleeping\", \"and\", \"eating\"." 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "# TODO: insert solution here" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "### ** Exercise**\n", 126 | "\n", 127 | "Assign the length of `word_list` to `num_words_int` and print" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "# TODO: insert solution here" 137 | ] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "### ** Exercise**\n", 144 | "\n", 145 | "Loop through each element in `word_list`, printing the index of the element and the element." 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "# TODO: insert solution here" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "metadata": {}, 160 | "source": [ 161 | "### ** Exercise**\n", 162 | "\n", 163 | "Loop through each element in `word_list`, printing the current element and the next element, separated by a space, in each loop\n", 164 | "\n", 165 | "Use the format:\n", 166 | "```python\n", 167 | "for i in range ... :\n", 168 | " phrase_str = ...\n", 169 | " print(phrase_str)\n", 170 | "```" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": {}, 177 | "outputs": [], 178 | "source": [ 179 | "# TODO: insert solution here" 180 | ] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "### ** Exercise**\n", 187 | "\n", 188 | "Loop through each element of the list, adding a space to them and then concatenating the result to an empty string called `dog_str` " 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "# TODO: insert solution here" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": {}, 203 | "source": [ 204 | "### ** Exercise**\n", 205 | "\n", 206 | "Loop through `nums_list`, multiplying each element by 3 and adding to a `new_nums_list`. Print `new_nums_list`." 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": null, 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "nums_list = [1,2,3,5,7]" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "# TODO: insert solution here" 225 | ] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "metadata": {}, 230 | "source": [ 231 | "### ** Exercise**\n", 232 | "\n", 233 | "Do the same exercise as above, but using a list comprehension." 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "# TODO: insert solution here" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "### ** Exercise**\n", 250 | "\n", 251 | "Loop through `ages_dict`, printing the names and ages in the dictionary." 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": null, 257 | "metadata": {}, 258 | "outputs": [], 259 | "source": [ 260 | "ages_dict = {'Ashley': 30, 'Emily': 33, 'Kurt': 28}" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "# TODO: insert solution here" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "metadata": {}, 275 | "source": [ 276 | "### ** Exercise**\n", 277 | "\n", 278 | "Loop through `ages_dict`, lowercasing the names and adding 10 to the ages in the dictionary and printing." 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": null, 284 | "metadata": {}, 285 | "outputs": [], 286 | "source": [ 287 | "# TODO: insert solution here" 288 | ] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "metadata": {}, 293 | "source": [ 294 | "### ** Exercise**\n", 295 | "\n", 296 | "Do the same exercise as above, but using a dictionary comprehension where the lowercase names are the keys and the age plus 10 are the values. Assign the dictionary comprehension to a variable called `my_dict` and print." 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": null, 302 | "metadata": {}, 303 | "outputs": [], 304 | "source": [ 305 | "# TODO: insert solution here" 306 | ] 307 | } 308 | ], 309 | "metadata": { 310 | "kernelspec": { 311 | "display_name": "Python 3", 312 | "language": "python", 313 | "name": "python3" 314 | }, 315 | "language_info": { 316 | "codemirror_mode": { 317 | "name": "ipython", 318 | "version": 3 319 | }, 320 | "file_extension": ".py", 321 | "mimetype": "text/x-python", 322 | "name": "python", 323 | "nbconvert_exporter": "python", 324 | "pygments_lexer": "ipython3", 325 | "version": "3.8.8" 326 | } 327 | }, 328 | "nbformat": 4, 329 | "nbformat_minor": 4 330 | } 331 | -------------------------------------------------------------------------------- /week_2/day_2_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "### ** Exercise**\n", 12 | "\n", 13 | "Given a dictionary of temperatures, please convert the Celsius values to Fahrenheit and update the dictionary. The equation to convert from Celsius to Fahrenheit is below. Please note that the temperature values are strings and not numbers!\n", 14 | "\n", 15 | "Fahrenheit = (Celsius * 9/5) + 32" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": null, 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "weather_dict = {}\n", 25 | "weather_dict['May 1'] = '15C'\n", 26 | "weather_dict['May 2'] = '10C'\n", 27 | "weather_dict['May 3'] = '8C'\n", 28 | "weather_dict['May 4'] = '9C'\n", 29 | "weather_dict['May 5'] = '17C'\n", 30 | "weather_dict['May 6'] = '20C'\n", 31 | "weather_dict['May 7'] = '22C'\n", 32 | "weather_dict['May 8'] = '20C'" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "# TODO: insert solution here" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "metadata": {}, 47 | "source": [ 48 | "### ** Exercise**\n", 49 | "\n", 50 | "Given a string, create a dictionary which has two keys 'vowel' and 'consonant' and the values are the number of vowels and consonants in the string. Test your code with a couple of simple words to make sure it works correctly." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "# TODO: insert solution here" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "### ** Exercise**\n", 67 | "\n", 68 | "What happens if your string contains capital letters or numbers or any other non-alpha characters? Fix your code to work correctly under thosee conditions! \n", 69 | "\n", 70 | "Hint: use the `.isalpha()` method. `char.isalpha()` returns `True` if `char` is in the alphabet, `False` otherwise.\n", 71 | "\n", 72 | "Some strings you should try:\n", 73 | "\n", 74 | "'Apple'\n", 75 | "\n", 76 | "'5 apples'\n", 77 | "\n", 78 | "'I like apples!'" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "# TODO: insert solution here" 88 | ] 89 | } 90 | ], 91 | "metadata": { 92 | "kernelspec": { 93 | "display_name": "Python 3", 94 | "language": "python", 95 | "name": "python3" 96 | }, 97 | "language_info": { 98 | "codemirror_mode": { 99 | "name": "ipython", 100 | "version": 3 101 | }, 102 | "file_extension": ".py", 103 | "mimetype": "text/x-python", 104 | "name": "python", 105 | "nbconvert_exporter": "python", 106 | "pygments_lexer": "ipython3", 107 | "version": "3.8.8" 108 | } 109 | }, 110 | "nbformat": 4, 111 | "nbformat_minor": 4 112 | } 113 | -------------------------------------------------------------------------------- /week_2/day_3_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "### ** Exercise**\n", 12 | "\n", 13 | "Using the following dictionaries, create a list called `students` that contains lloyd, alice, and tyler." 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "lloyd = {\n", 23 | " \"name\": \"Lloyd\",\n", 24 | " \"homework\": [90.0, 97.0, 75.0, 92.0],\n", 25 | " \"quizzes\": [88.0, 40.0, 94.0],\n", 26 | " \"tests\": [75.0, 90.0]\n", 27 | "}\n", 28 | "alice = {\n", 29 | " \"name\": \"Alice\",\n", 30 | " \"homework\": [100.0, 92.0, 98.0, 100.0],\n", 31 | " \"quizzes\": [82.0, 83.0, 91.0],\n", 32 | " \"tests\": [89.0, 97.0]\n", 33 | "}\n", 34 | "tyler = {\n", 35 | " \"name\": \"Tyler\",\n", 36 | " \"homework\": [0.0, 87.0, 75.0, 22.0],\n", 37 | " \"quizzes\": [0.0, 75.0, 78.0],\n", 38 | " \"tests\": [100.0, 100.0]\n", 39 | "}" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "# TODO: insert solution here" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "### ** Exercise**\n", 56 | "\n", 57 | "Write a function `average()` that takes a list of numbers and returns the average.\n", 58 | "\n", 59 | "* Inside that function, call the built-in `sum()` function with the numbers list as a parameter. Store the result in a variable called `total`.\n", 60 | "* Divide `total` by the length of the numbers list. Use the built-in `len()` function to calculate that.\n", 61 | "* Return that result.\n", 62 | "\n", 63 | "Test your function. Call your `average()` function with `[1,2,3]`. Assign the resulting average to a variable called `avg_flt` and print." 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "# TODO: insert solution here" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "### ** Exercise**\n", 80 | "\n", 81 | "Write a function called `get_average()` that takes a student dictionary (like `lloyd`, `alice`, or `tyler`) as input and returns the student's weighted average.\n", 82 | "\n", 83 | "* Make a variable `homework` that stores the `average()` of `student[\"homework\"]`.\n", 84 | "* Repeat step 2 for `quizzes` and `tests`.\n", 85 | "* Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.\n", 86 | "\n", 87 | "Test your function. Call your `get_average()` function with `lloyd` and set the result to a variable called `lloyd_avg_flt`. Print the resulting average grade." 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "# TODO: insert solution here" 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": {}, 102 | "source": [ 103 | "### ** Exercise**\n", 104 | "\n", 105 | "Define a new function called `get_letter_grade()` that has one argument called `score`. Expect `score` to be a number.\n", 106 | "\n", 107 | "Inside your function, test `score` using a chain of `if:` / `elif:` / `else:` statements, like so:\n", 108 | "\n", 109 | "* If score is 90 or above: return \"A\"\n", 110 | "* Else if score is 80 or above: return \"B\"\n", 111 | "* Else if score is 70 or above: return \"C\"\n", 112 | "* Else if score is 60 or above: return \"D\"\n", 113 | "* Otherwise: return \"F\"\n", 114 | "\n", 115 | "Finally, test your function. Call your `get_letter_grade()` function with the result of `get_average(lloyd)` and assign the result to a variable called `lloyd_avg_str`. Print the resulting letter grade." 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "# TODO: insert solution here" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "### ** Exercise**\n", 132 | "\n", 133 | "Define a function called `get_class_average()` that has one argument, `students`. You can expect `students` to be a list containing your three students.\n", 134 | "\n", 135 | "* First, make an empty list called `results`.\n", 136 | "* For each student item in the class list, calculate `get_average(student)` and then call `results.append()` with that result.\n", 137 | "* Finally, return the result of calling `average()` with `results`.\n", 138 | "* Finally, assign the result of calling `get_class_average()` with your `students` list to a variable called `class_avg_flt` and print. Your students should be `[lloyd, alice, tyler]`." 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "# TODO: insert solution here" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "Then, assign the result of `get_letter_grade()` for the class's average to a variable called `class_avg_str` and print." 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "# TODO: insert solution here" 164 | ] 165 | } 166 | ], 167 | "metadata": { 168 | "kernelspec": { 169 | "display_name": "Python 3", 170 | "language": "python", 171 | "name": "python3" 172 | }, 173 | "language_info": { 174 | "codemirror_mode": { 175 | "name": "ipython", 176 | "version": 3 177 | }, 178 | "file_extension": ".py", 179 | "mimetype": "text/x-python", 180 | "name": "python", 181 | "nbconvert_exporter": "python", 182 | "pygments_lexer": "ipython3", 183 | "version": "3.8.8" 184 | } 185 | }, 186 | "nbformat": 4, 187 | "nbformat_minor": 4 188 | } 189 | -------------------------------------------------------------------------------- /week_2/day_3_lecture.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "#
LECTURE OVERVIEW
\n", 12 | "\n", 13 | "---\n", 14 | "\n", 15 | "## By the end of the day you'll be able to:\n", 16 | "- write simple functions\n", 17 | "- write functions with multiple arguments and outputs\n", 18 | "- write functions with named arguments and default argument values\n", 19 | "- describe the difference between global and local scope\n", 20 | "- handle errors within your code\n", 21 | "\n", 22 | "#
FUNCTIONS
\n", 23 | "\n", 24 | "---\n", 25 | "\n", 26 | "# Defining Functions\n", 27 | "\n", 28 | "## By the end of the day you'll be able to:\n", 29 | "- **write simple functions**\n", 30 | "- write functions with multiple arguments and outputs\n", 31 | "- write functions with named arguments and default argument values\n", 32 | "- describe the difference between global and local scope\n", 33 | "- handle errors within your code\n", 34 | "\n", 35 | "Functions are discrete units of code\n", 36 | "- Similar to functions in mathematics\n", 37 | " - Take some input, return some output (_usually_)\n", 38 | "- Have a very specific syntax that uses indentation and special keywords that let Python know you are defining or creating a new function\n", 39 | "\n", 40 | "```python\n", 41 | "def function_name(argument):\n", 42 | " # do something here\n", 43 | " # etc\n", 44 | " return # something\n", 45 | "```" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": { 52 | "slideshow": { 53 | "slide_type": "subslide" 54 | } 55 | }, 56 | "outputs": [], 57 | "source": [ 58 | "# Define simple function.\n", 59 | "# Note: Indentation used to denote function body\n", 60 | "# Note: The lines within def are only run when you call the function\n", 61 | "\n", 62 | "def add_one(number):\n", 63 | " res = number + 1\n", 64 | " return res\n", 65 | "\n", 66 | "res1_int = add_one(42)\n", 67 | "res2_int = add_one(9)\n", 68 | "print(res1_int)\n", 69 | "print(res2_int)" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "metadata": {}, 75 | "source": [ 76 | "When defining a function, you can call another function you already defined." 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "def is_even(n):\n", 86 | " res = n % 2 == 0\n", 87 | " return res\n", 88 | "\n", 89 | "res1_int = is_even(17)\n", 90 | "res2_int = is_even(2)\n", 91 | "\n", 92 | "print(res1_int)\n", 93 | "print(res2_int)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "def is_odd(n):\n", 103 | " res = not is_even(n)\n", 104 | " return res\n", 105 | "\n", 106 | "res1_int = is_odd(30)\n", 107 | "res2_int = is_odd(31)\n", 108 | "\n", 109 | "print(res1_int) \n", 110 | "print(res2_int)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### ** Exercise**\n", 118 | "\n", 119 | "Define a function that takes a number as input, multiplies it by 2, and returns the result. Test your function on a few examples: 1, 9, 19. Assign the results to variables named `res1_int`, `res2_int`, and `res3_int`. Print the results." 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "metadata": {}, 126 | "outputs": [], 127 | "source": [ 128 | "# TODO: insert solution here" 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "metadata": {}, 134 | "source": [ 135 | "### ** Exercise**\n", 136 | "\n", 137 | "Define a function that takes a number as input, multiplies it by 2 using `times_two()`, subtracts 4, and returns the result. Test your function on a few examples: 1, 9, 19. Assign the results to variables named `res1_int`, `res2_int`, and `res3_int`. Print the results." 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "# TODO: insert solution here" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": { 152 | "slideshow": { 153 | "slide_type": "subslide" 154 | } 155 | }, 156 | "source": [ 157 | "# Functions with Multiple Arguments\n", 158 | "\n", 159 | "## By the end of the day you'll be able to:\n", 160 | "- write simple functions\n", 161 | "- **write functions with multiple arguments and outputs**\n", 162 | "- write functions with named arguments and default argument values\n", 163 | "- describe the difference between global and local scope\n", 164 | "- handle errors within your code" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": null, 170 | "metadata": { 171 | "slideshow": { 172 | "slide_type": "-" 173 | } 174 | }, 175 | "outputs": [], 176 | "source": [ 177 | "def combine_strings(string_1, string_2):\n", 178 | " res = string_1 + ' ' + string_2\n", 179 | " return res \n", 180 | "\n", 181 | "res1_str = combine_strings('hello', 'world')\n", 182 | "res2_str = combine_strings('goodbye', 'moon')\n", 183 | "\n", 184 | "print(res1_str)\n", 185 | "print(res2_str)" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": { 191 | "slideshow": { 192 | "slide_type": "subslide" 193 | } 194 | }, 195 | "source": [ 196 | "### ** Exercise**\n", 197 | "\n", 198 | "Define a function that adds two numbers and returns the result. Test your function on a few pairs - (5, 9) and (10, 20) - and assign the results to variables named `res1_int` and `res2_int`. Print the results." 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "# TODO: insert solution here" 208 | ] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "metadata": { 213 | "slideshow": { 214 | "slide_type": "subslide" 215 | } 216 | }, 217 | "source": [ 218 | "### ** Exercise**\n", 219 | "\n", 220 | "Let's write a function that finds the mean of two numbers. The function should call the `add_vals()` function we defined above and divide the result by two. Test the function on some example pairs (e.g., (10, 20) and (16, 16)) and assign the results to variables named `res1_flt` and `res2_flt`. Print the results." 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "# TODO: insert solution here" 230 | ] 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "metadata": { 235 | "slideshow": { 236 | "slide_type": "subslide" 237 | } 238 | }, 239 | "source": [ 240 | "# Functions with Multiple Outputs\n", 241 | "\n", 242 | "## By the end of the day you'll be able to:\n", 243 | "- write simple functions\n", 244 | "- write functions with multiple arguments and outputs\n", 245 | "- **write functions with named arguments and default argument values**\n", 246 | "- describe the difference between global and local scope\n", 247 | "- handle errors within your code" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "metadata": { 254 | "slideshow": { 255 | "slide_type": "-" 256 | } 257 | }, 258 | "outputs": [], 259 | "source": [ 260 | "from statistics import mean, stdev\n", 261 | "\n", 262 | "def mean_sd(numbers_list):\n", 263 | " m = mean(numbers_list)\n", 264 | " sd = stdev(numbers_list)\n", 265 | " return m, sd\n", 266 | "\n", 267 | "mean_flt, sd_flt = mean_sd([0, 2, 10, 10])\n", 268 | "print(mean_flt, sd_flt)" 269 | ] 270 | }, 271 | { 272 | "cell_type": "markdown", 273 | "metadata": { 274 | "slideshow": { 275 | "slide_type": "subslide" 276 | } 277 | }, 278 | "source": [ 279 | "### ** Exercise**\n", 280 | "\n", 281 | "Write a function that takes as input two values, and return two outputs: the sum and the product of the two values. Test on a few example pairs (e.g., (10, 20) and (5, 9)) and assign the results to variables named `a1_int, a2_int` and `b1_int, b2_int`. Print the results" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "# TODO: insert solution here" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "metadata": { 296 | "slideshow": { 297 | "slide_type": "subslide" 298 | } 299 | }, 300 | "source": [ 301 | "# Using Keyword Arguments\n", 302 | "\n", 303 | "- So far, we been using \"positional\" matching of arguments\n", 304 | "- More complicated functions can take many arguments\n", 305 | "- Remembering the order of the arguments can get tricky\n", 306 | "- Python allows \"keyword\" arguments" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": null, 312 | "metadata": { 313 | "slideshow": { 314 | "slide_type": "subslide" 315 | } 316 | }, 317 | "outputs": [], 318 | "source": [ 319 | "def make_sentence(subj, verb, obj):\n", 320 | " res = subj + \" \" + verb + \" \" + obj\n", 321 | " return res" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": { 328 | "slideshow": { 329 | "slide_type": "-" 330 | } 331 | }, 332 | "outputs": [], 333 | "source": [ 334 | "# Run our function with positional arguments\n", 335 | "make_sentence(\"paul\", \"ate\", \"the potato\")" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "metadata": { 342 | "slideshow": { 343 | "slide_type": "-" 344 | } 345 | }, 346 | "outputs": [], 347 | "source": [ 348 | "# Change order of positional arguments\n", 349 | "make_sentence(\"the potato\", \"ate\", \"paul\")" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "metadata": { 356 | "slideshow": { 357 | "slide_type": "-" 358 | } 359 | }, 360 | "outputs": [], 361 | "source": [ 362 | "# Change order of keyword arguments\n", 363 | "make_sentence(obj=\"the potato\", verb=\"ate\", subj=\"paul\")" 364 | ] 365 | }, 366 | { 367 | "cell_type": "markdown", 368 | "metadata": { 369 | "slideshow": { 370 | "slide_type": "subslide" 371 | } 372 | }, 373 | "source": [ 374 | "# Default Argument Values\n", 375 | "- Can specify defaults for some (or all) arguments" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": { 382 | "slideshow": { 383 | "slide_type": "-" 384 | } 385 | }, 386 | "outputs": [], 387 | "source": [ 388 | "def make_sentence(subj, verb, obj='the potato'):\n", 389 | " res = subj + \" \" + verb + \" \" + obj\n", 390 | " return res\n", 391 | "\n", 392 | "print(make_sentence('Ashley', 'hates'))" 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "execution_count": null, 398 | "metadata": { 399 | "slideshow": { 400 | "slide_type": "-" 401 | } 402 | }, 403 | "outputs": [], 404 | "source": [ 405 | "print(make_sentence('Ashley', 'hates', 'the croissant'))" 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": null, 411 | "metadata": { 412 | "slideshow": { 413 | "slide_type": "subslide" 414 | } 415 | }, 416 | "outputs": [], 417 | "source": [ 418 | "print(make_sentence(verb='hates', subj='Ashley', obj='the croissant'))" 419 | ] 420 | }, 421 | { 422 | "cell_type": "code", 423 | "execution_count": null, 424 | "metadata": { 425 | "slideshow": { 426 | "slide_type": "-" 427 | } 428 | }, 429 | "outputs": [], 430 | "source": [ 431 | "print(make_sentence(verb='hates', subj='Ashley'))" 432 | ] 433 | }, 434 | { 435 | "cell_type": "markdown", 436 | "metadata": { 437 | "slideshow": { 438 | "slide_type": "subslide" 439 | } 440 | }, 441 | "source": [ 442 | "### ** Exercise**\n", 443 | "\n", 444 | "Write a function that concatenates two words together with a space between the words. The second word should have a default value of 'ran'. Test your function on `dog` and `dog, ate` and assign the results to `res1_str` and `res2_str`." 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": null, 450 | "metadata": {}, 451 | "outputs": [], 452 | "source": [ 453 | "# TODO: insert solution here" 454 | ] 455 | }, 456 | { 457 | "cell_type": "markdown", 458 | "metadata": { 459 | "slideshow": { 460 | "slide_type": "subslide" 461 | } 462 | }, 463 | "source": [ 464 | "# Scope and Functions\n", 465 | "\n", 466 | "## By the end of the day you'll be able to:\n", 467 | "- write simple functions\n", 468 | "- write functions with multiple arguments and outputs\n", 469 | "- write functions with named arguments and default argument values\n", 470 | "- **describe the difference between global and local scope**\n", 471 | "- handle errors within your code\n", 472 | "\n", 473 | "The scope of a variable refers to the places where you have access it.\n", 474 | "\n", 475 | "- Global scope can be considered the top level\n", 476 | "- Functions introduce \"local scope\"" 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": null, 482 | "metadata": { 483 | "slideshow": { 484 | "slide_type": "subslide" 485 | } 486 | }, 487 | "outputs": [], 488 | "source": [ 489 | "# local variables cannot be used in the global scope, only the local scope\n", 490 | "def breakfast(is_ham):\n", 491 | " is_eggs = True\n", 492 | " if is_ham == True:\n", 493 | " is_bacon = False\n", 494 | " else:\n", 495 | " is_bacon = True \n", 496 | " return is_eggs, is_bacon\n", 497 | "\n", 498 | "eggs_bool, bacon_bool = breakfast(True)\n", 499 | "print(eggs_bool)\n", 500 | "print(bacon_bool)" 501 | ] 502 | }, 503 | { 504 | "cell_type": "markdown", 505 | "metadata": {}, 506 | "source": [ 507 | "### **Caution**" 508 | ] 509 | }, 510 | { 511 | "cell_type": "code", 512 | "execution_count": null, 513 | "metadata": {}, 514 | "outputs": [], 515 | "source": [ 516 | "print(is_eggs)" 517 | ] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "execution_count": null, 522 | "metadata": { 523 | "slideshow": { 524 | "slide_type": "subslide" 525 | } 526 | }, 527 | "outputs": [], 528 | "source": [ 529 | "# global variables can be read from global to local scope\n", 530 | "def breakfast():\n", 531 | " print(eggs_str)\n", 532 | " \n", 533 | "eggs_str = 'over easy'\n", 534 | "breakfast()" 535 | ] 536 | }, 537 | { 538 | "cell_type": "markdown", 539 | "metadata": {}, 540 | "source": [ 541 | "Don't use the same variable name from **global to local scope**.\n", 542 | "\n", 543 | "It's okay to use the same variable name from **local to global scope** since the local variable will be trashed once the function call is done executing." 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": null, 549 | "metadata": { 550 | "slideshow": { 551 | "slide_type": "subslide" 552 | } 553 | }, 554 | "outputs": [], 555 | "source": [ 556 | "def chop(input_string):\n", 557 | " split_string = input_string.split()\n", 558 | " return split_string\n", 559 | "\n", 560 | "my_string = 'hi hello hey'\n", 561 | "split_string = chop(my_string)\n", 562 | "print(split_string)" 563 | ] 564 | }, 565 | { 566 | "cell_type": "markdown", 567 | "metadata": { 568 | "slideshow": { 569 | "slide_type": "subslide" 570 | } 571 | }, 572 | "source": [ 573 | "# Exception Handling\n", 574 | "\n", 575 | "## By the end of the day you'll be able to:\n", 576 | "- write simple functions\n", 577 | "- write functions with multiple arguments and outputs\n", 578 | "- write functions with named arguments and default argument values\n", 579 | "- describe the difference between global and local scope\n", 580 | "- **handle errors within your code**\n", 581 | "\n", 582 | "As we have written code up until now, getting an error (or exception) can be difficult to decipher. Instead, we can detect errors and handle them while customizing error messages for transparency." 583 | ] 584 | }, 585 | { 586 | "cell_type": "code", 587 | "execution_count": null, 588 | "metadata": { 589 | "slideshow": { 590 | "slide_type": "-" 591 | } 592 | }, 593 | "outputs": [], 594 | "source": [ 595 | "def reverse(input_string):\n", 596 | " rev_string = input_string[::-1]\n", 597 | " return rev_string\n", 598 | "\n", 599 | "reverse(\"NOPE\")" 600 | ] 601 | }, 602 | { 603 | "cell_type": "code", 604 | "execution_count": null, 605 | "metadata": { 606 | "slideshow": { 607 | "slide_type": "-" 608 | } 609 | }, 610 | "outputs": [], 611 | "source": [ 612 | "reverse(999)" 613 | ] 614 | }, 615 | { 616 | "cell_type": "code", 617 | "execution_count": null, 618 | "metadata": { 619 | "slideshow": { 620 | "slide_type": "subslide" 621 | } 622 | }, 623 | "outputs": [], 624 | "source": [ 625 | "def reverse(input_string):\n", 626 | " try:\n", 627 | " rev_string = input_string[::-1]\n", 628 | " return rev_string\n", 629 | " except:\n", 630 | " raise TypeError(\"`input_string` must be a string\")\n", 631 | " return None\n", 632 | " \n", 633 | "reverse(999)" 634 | ] 635 | }, 636 | { 637 | "cell_type": "markdown", 638 | "metadata": { 639 | "slideshow": { 640 | "slide_type": "subslide" 641 | } 642 | }, 643 | "source": [ 644 | "For more exception types, see the [documentation](https://docs.python.org/3/library/exceptions.html#bltin-exceptions).\n", 645 | "\n", 646 | "### ** Exercise**\n", 647 | "\n", 648 | "Write a function that adds 2 to a number. Handle the error that would occur if you passed a string to the function. Test your function on `9` and `hello`" 649 | ] 650 | }, 651 | { 652 | "cell_type": "code", 653 | "execution_count": null, 654 | "metadata": {}, 655 | "outputs": [], 656 | "source": [ 657 | "# TODO: insert solution here" 658 | ] 659 | }, 660 | { 661 | "cell_type": "markdown", 662 | "metadata": {}, 663 | "source": [ 664 | "# Conclusion\n", 665 | "\n", 666 | "## You are now able to:\n", 667 | "- write simple functions\n", 668 | "- write functions with multiple arguments and outputs\n", 669 | "- write functions with named arguments and default argument values\n", 670 | "- describe the difference between global and local scope\n", 671 | "- handle errors within your code" 672 | ] 673 | } 674 | ], 675 | "metadata": { 676 | "celltoolbar": "Slideshow", 677 | "kernelspec": { 678 | "display_name": "Python 3", 679 | "language": "python", 680 | "name": "python3" 681 | }, 682 | "language_info": { 683 | "codemirror_mode": { 684 | "name": "ipython", 685 | "version": 3 686 | }, 687 | "file_extension": ".py", 688 | "mimetype": "text/x-python", 689 | "name": "python", 690 | "nbconvert_exporter": "python", 691 | "pygments_lexer": "ipython3", 692 | "version": "3.8.8" 693 | } 694 | }, 695 | "nbformat": 4, 696 | "nbformat_minor": 4 697 | } 698 | -------------------------------------------------------------------------------- /week_2/day_4_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "### ** Exercise**\n", 12 | "\n", 13 | "Write a function that takes a string as input and it returns whether the string is a valid password (the return value is True) or not (the return value is False). A string is a valid password if :\n", 14 | "- it contains least 1 number between 0 and 9,\n", 15 | "- if it contains at least 1 character from the list `['$','#','@','.','!','?','<','>']`,\n", 16 | "- if it has a minimum length of at least 6 characters.\n", 17 | "\n", 18 | "Please check that the input to the function is indeed a string. If it is not, print a diagnostic message and raise a value error.\n", 19 | "\n", 20 | "Test your function with the strings below to make sure it works correctly. Note how the test strings try all possible ways the conditions can fail. You should aim to test your code with such thoroughness.\n", 21 | "\n", 22 | "```\n", 23 | "'ilikeplums!' => False (fails on first condition)\n", 24 | "\n", 25 | "'plum2020' => False (fails on second condition)\n", 26 | "\n", 27 | "'a2b3?' => False (fails on third condition)\n", 28 | "\n", 29 | "'applesaretasty' => False (fails on the first and second conditionss)\n", 30 | "\n", 31 | "'plum!' => False (fails on first and third conditions)\n", 32 | "\n", 33 | "'plum5' => False (fails on second and third conditions)\n", 34 | "\n", 35 | "'apple' => False (fails all three conditions)\n", 36 | "\n", 37 | "'1234' => True\n", 38 | "\n", 39 | "'!p1umsareblue' => True\n", 40 | "```" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 1, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# TODO: insert solution here" 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "### ** Exercise**\n", 57 | "\n", 58 | "Write a function which takes a list of strings as input and it returns a list of booleans that are true for valid password strings and false otherwise. Call the function you wrote in exercise 1. Please check that the input to the function is indeed a list. If it is not, print a diagnostic message and raise a value error.\n", 59 | "\n", 60 | "Call the function with the list below and verify that the output list is correct." 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 5, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "# TODO: insert solution here" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "metadata": {}, 75 | "source": [ 76 | "### ** Exercise**\n", 77 | "\n", 78 | "Write a function that takes a list as input and returns a new list with the unique elements of the input list. For example, if the input is `[1,2,5,5,2,3,4,1,3]`, it returns `[1,2,5,3,4]`. The function should work with a list of strings or any other item types.\n", 79 | "\n", 80 | "As before, please check that the input is indeed a list and do the usual things if it is not.\n", 81 | "\n", 82 | "Come up with input lists to test your algorithm! " 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "# TODO: insert solution here" 92 | ] 93 | } 94 | ], 95 | "metadata": { 96 | "kernelspec": { 97 | "display_name": "Python 3", 98 | "language": "python", 99 | "name": "python3" 100 | }, 101 | "language_info": { 102 | "codemirror_mode": { 103 | "name": "ipython", 104 | "version": 3 105 | }, 106 | "file_extension": ".py", 107 | "mimetype": "text/x-python", 108 | "name": "python", 109 | "nbconvert_exporter": "python", 110 | "pygments_lexer": "ipython3", 111 | "version": "3.8.8" 112 | } 113 | }, 114 | "nbformat": 4, 115 | "nbformat_minor": 4 116 | } 117 | -------------------------------------------------------------------------------- /week_2/day_4_lecture.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "#
LECTURE OVERVIEW
\n", 12 | "\n", 13 | "---\n", 14 | "\n", 15 | "We covered a lot so far!\n", 16 | "\n", 17 | "- variables\n", 18 | "- container types\n", 19 | "- control flow (`if` statements and `for` loops)\n", 20 | "- functions\n", 21 | "\n", 22 | "Very little new material today. We will practice everything we learnt so far.\n", 23 | "\n", 24 | "## By the end of the day you'll be able to:\n", 25 | "- test your function inputs\n", 26 | "\n", 27 | "#
TESTING
\n", 28 | "\n", 29 | "---\n", 30 | "\n", 31 | "# Testing your Code\n", 32 | "\n", 33 | "## By the end of the day you'll be able to:\n", 34 | "- **test your function inputs**\n", 35 | "\n", 36 | "## Type of errors\n", 37 | "1. obvious errors that give you an error message\n", 38 | " - usually syntax errors, forgotten `:`, type error, forgotten tabs, etc.\n", 39 | " - it can be quickly resolved with some googling\n", 40 | "2. sneaky errors that don't throw an error message\n", 41 | " - your code runs but the results are incorrect\n", 42 | " - it can only be caught by extensive testing " 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": { 48 | "slideshow": { 49 | "slide_type": "subslide" 50 | } 51 | }, 52 | "source": [ 53 | "Test-driven development is encouraged!\n", 54 | " - figure out how you'll test your code even before you start writing it\n", 55 | "\n", 56 | "Test your data!\n", 57 | " - what properties do you expect the data to have?\n", 58 | " - test those!\n", 59 | " - errors in data collection often occur" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": { 65 | "slideshow": { 66 | "slide_type": "slide" 67 | } 68 | }, 69 | "source": [ 70 | "## How to test your data?\n", 71 | "\n", 72 | "- consider what properties the input data to your functions should have:\n", 73 | " - age should be larger than 0 but smaller than ~150\n", 74 | " - sounds obvious but negative values or values over 200 can occur due to typos\n", 75 | " - salary should be positive\n", 76 | " - names should not contain non-alpha characters like numbers or special characters" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 33, 82 | "metadata": {}, 83 | "outputs": [ 84 | { 85 | "name": "stdout", 86 | "output_type": "stream", 87 | "text": [ 88 | "{'employee1': {'salary': 50000, 'gender': 'male', 'age': 39}, 'employee2': {'salary': 70000, 'gender': 'female', 'age': 46}, 'employee3': {'salary': 60000, 'gender': 'female', 'age': 556}, 'employee4': {'salary': 130000, 'gender': 'male', 'age': 60}, 'employee5': {'salary': 80000, 'gender': 'female', 'age': 29}, 'employee6': {'salary': 40000, 'gender': 'female', 'age': 45}, 'employee7': {'salary': 70000, 'gender': 'male', 'age': 34}, 'employee8': {'salary': 50000, 'gender': 'male', 'age': 101}}\n" 89 | ] 90 | } 91 | ], 92 | "source": [ 93 | "employees_dict = {}\n", 94 | "employees_dict['employee1'] = [50000, 'male', 39] # salary, gender, age\n", 95 | "employees_dict['employee2'] = [70000, 'female', 46]\n", 96 | "employees_dict['employee3'] = [60000, 'female', 556]\n", 97 | "employees_dict['employee4'] = [130000, 'male', 60]\n", 98 | "employees_dict['employee5'] = [80000, 'female', 29]\n", 99 | "employees_dict['employee6'] = [40000, 'female', 45]\n", 100 | "employees_dict['employee7'] = [70000, 'male', 34]\n", 101 | "employees_dict['employee8'] = [50000, 'male', 101]\n", 102 | "\n", 103 | "employees_dict = {\n", 104 | " emp: {'salary': emp_info[0], 'gender': emp_info[1], 'age': emp_info[2]}\n", 105 | " for emp, emp_info in employees_dict.items()\n", 106 | "}\n", 107 | "print(employees_dict)" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 34, 113 | "metadata": { 114 | "slideshow": { 115 | "slide_type": "subslide" 116 | } 117 | }, 118 | "outputs": [ 119 | { 120 | "name": "stdout", 121 | "output_type": "stream", 122 | "text": [ 123 | "Error data: employee3 {'salary': 60000, 'gender': 'female', 'age': 556}\n" 124 | ] 125 | }, 126 | { 127 | "ename": "ValueError", 128 | "evalue": "age is unrealistic", 129 | "output_type": "error", 130 | "traceback": [ 131 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 132 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", 133 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'age is unrealistic'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 17\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 18\u001b[0;31m \u001b[0mtest_employee_dictionary\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0memployees_dict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 134 | "\u001b[0;32m\u001b[0m in \u001b[0;36mtest_employee_dictionary\u001b[0;34m(input_dict)\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0memp_info_dict\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'age'\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0;36m150\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Error data:\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0memp\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0memp_info_dict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 16\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'age is unrealistic'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 17\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 18\u001b[0m \u001b[0mtest_employee_dictionary\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0memployees_dict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 135 | "\u001b[0;31mValueError\u001b[0m: age is unrealistic" 136 | ] 137 | } 138 | ], 139 | "source": [ 140 | "# let's test data first\n", 141 | "def test_employee_dictionary(input_dict):\n", 142 | " # let's iterate through each key-value pair and write tests\n", 143 | " for emp, emp_info_dict in input_dict.items():\n", 144 | " # salary should be positive\n", 145 | " if emp_info_dict['salary'] < 0:\n", 146 | " print(\"DataError:\", emp, emp_info_dict)\n", 147 | " raise ValueError('salary is negative')\n", 148 | " # gender should be 'male' or 'female'\n", 149 | " if emp_info_dict['gender'] not in ['male', 'female']:\n", 150 | " print(\"DataError:\", emp, emp_info_dict)\n", 151 | " raise ValueError('unrecognized gender value')\n", 152 | " # age should be between 0 and 150\n", 153 | " if not (0 <= emp_info_dict['age'] <= 150):\n", 154 | " print(\"DataError:\", emp, emp_info_dict)\n", 155 | " raise ValueError('age is unrealistic')\n", 156 | "\n", 157 | "test_employee_dictionary(employees_dict)" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 36, 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "{'employee1': {'salary': 50000, 'gender': 'male', 'age': 39}, 'employee2': {'salary': 70000, 'gender': 'female', 'age': 46}, 'employee4': {'salary': 130000, 'gender': 'male', 'age': 60}, 'employee5': {'salary': 80000, 'gender': 'female', 'age': 29}, 'employee6': {'salary': 40000, 'gender': 'female', 'age': 45}, 'employee7': {'salary': 70000, 'gender': 'male', 'age': 34}, 'employee8': {'salary': 50000, 'gender': 'male', 'age': 101}}\n" 170 | ] 171 | } 172 | ], 173 | "source": [ 174 | "employees_dict = {}\n", 175 | "employees_dict['employee1'] = [50000, 'male', 39] # salary, gender, age\n", 176 | "employees_dict['employee2'] = [70000, 'female', 46]\n", 177 | "# employees_dict['employee3'] = [60000, 'female', 556]\n", 178 | "employees_dict['employee4'] = [130000, 'male', 60]\n", 179 | "employees_dict['employee5'] = [80000, 'female', 29]\n", 180 | "employees_dict['employee6'] = [40000, 'female', 45]\n", 181 | "employees_dict['employee7'] = [70000, 'male', 34]\n", 182 | "employees_dict['employee8'] = [50000, 'male', 101]\n", 183 | "employees_dict = {\n", 184 | " emp: {'salary': emp_info[0], 'gender': emp_info[1], 'age': emp_info[2]}\n", 185 | " for emp, emp_info in employees_dict.items()\n", 186 | "}\n", 187 | "print(employees_dict)" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 37, 193 | "metadata": { 194 | "slideshow": { 195 | "slide_type": "slide" 196 | } 197 | }, 198 | "outputs": [ 199 | { 200 | "name": "stdout", 201 | "output_type": "stream", 202 | "text": [ 203 | "75000 63333.333333333336\n" 204 | ] 205 | } 206 | ], 207 | "source": [ 208 | "# let's compare the mean salaries of males and females\n", 209 | "def mean_salaries_by_gender(input_dict):\n", 210 | " # test the data\n", 211 | " test_employee_dictionary(input_dict)\n", 212 | " \n", 213 | " male_salaries, female_salaries = [], []\n", 214 | " for _, emp_info_dict in input_dict.items():\n", 215 | " if emp_info_dict['gender'] == 'male':\n", 216 | " male_salaries.append(emp_info_dict['salary'])\n", 217 | " else:\n", 218 | " female_salaries.append(emp_info_dict['salary'])\n", 219 | " \n", 220 | " mean_male_salary = sum(male_salaries) / len(male_salaries) if male_salaries != [] else 0\n", 221 | " mean_female_salary = sum(female_salaries) / len(female_salaries) if female_salaries != [] else 0\n", 222 | " \n", 223 | " return mean_male_salary, mean_female_salary\n", 224 | "\n", 225 | "male_sal_flt, female_sal_flt = mean_salaries_by_gender(employees_dict)\n", 226 | "print(male_sal_flt, female_sal_flt)" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": { 232 | "slideshow": { 233 | "slide_type": "slide" 234 | } 235 | }, 236 | "source": [ 237 | "### ** Exercise**\n", 238 | "\n", 239 | "Compare the mean salaries of people under 45 vs 45 and above. Call the function `mean_salaries_by_age()` and use `employees_dict`." 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": 38, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "# TODO: insert solution here" 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": { 254 | "slideshow": { 255 | "slide_type": "slide" 256 | } 257 | }, 258 | "source": [ 259 | "### ** Exercise**\n", 260 | "\n", 261 | "Modify the function such that the critical age (which was 45 years in exercise 1) is an input to the function and can be changed. Please check that this function returns the same result as before for critical_age = 45! What happens if you set critical age to 0 or to 100?" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": 40, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "# TODO: insert solution here" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "metadata": { 276 | "slideshow": { 277 | "slide_type": "slide" 278 | } 279 | }, 280 | "source": [ 281 | "### ** Exercise**\n", 282 | "\n", 283 | "Take the bubble sort algorithm from two days ago, wrap it in a function, and add a test on top to check if all items in the list are float or int. If there are non-numeric elements in the list, the code should print a diagnostic message and raise a value error." 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "# bubble sort algorithm\n", 293 | "for i in range(len(nums_lst)):\n", 294 | " for j in range(i):\n", 295 | " if nums_lst[j] > nums_lst[i]: # if an item is smaller than its neighbor, switch them\n", 296 | " temp = nums_lst[i] # temporary variable\n", 297 | " nums_lst[i] = nums_lst[j]\n", 298 | " nums_lst[j] = temp\n", 299 | " \n", 300 | "# list you need to use for testing. note that some elements are str, list, or boolean\n", 301 | "numbers_lst = [24, 76.4, 23, 86, 'f', [23, 6], True]" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": {}, 308 | "outputs": [], 309 | "source": [ 310 | "# TODO: insert solution here" 311 | ] 312 | }, 313 | { 314 | "cell_type": "markdown", 315 | "metadata": {}, 316 | "source": [ 317 | "# Conclusion\n", 318 | "\n", 319 | "## You are now able to:\n", 320 | "- test your function inputs" 321 | ] 322 | } 323 | ], 324 | "metadata": { 325 | "celltoolbar": "Slideshow", 326 | "kernelspec": { 327 | "display_name": "Python 3", 328 | "language": "python", 329 | "name": "python3" 330 | }, 331 | "language_info": { 332 | "codemirror_mode": { 333 | "name": "ipython", 334 | "version": 3 335 | }, 336 | "file_extension": ".py", 337 | "mimetype": "text/x-python", 338 | "name": "python", 339 | "nbconvert_exporter": "python", 340 | "pygments_lexer": "ipython3", 341 | "version": "3.8.8" 342 | } 343 | }, 344 | "nbformat": 4, 345 | "nbformat_minor": 4 346 | } 347 | -------------------------------------------------------------------------------- /week_3/day_1_assets/Cartesian_Product_qtl1.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 20 | 48 | 57 | 58 | 60 | 61 | 63 | image/svg+xml 64 | 66 | 67 | 68 | 69 | 70 | 75 | 84 | 90 | 96 | 106 | 112 | 118 | (z,1) 134 | (z,2) 150 | (z,3) 166 | (y,1) 182 | (y,2) 198 | (y,3) 214 | (x,1) 230 | (x,2) 246 | (x,3) 262 | 273 | 283 | 1 295 | 2 307 | 3 319 | z 331 | y 343 | x 355 | 364 | 374 | 384 | 395 | B 407 | A 419 | A×B 435 | 441 | 447 | 453 | 454 | 455 | -------------------------------------------------------------------------------- /week_3/day_1_assets/Permutations_RGB.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /week_3/day_1_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "## ** Exercise**\n", 12 | "\n", 13 | "You are in charge of managing the fruit for the community BBQ! The fruit donated is stored in `com_fruit` where each element in the list is `(fruit_name, num_fruit)` tuple. For instance, if someone donated 2 apples, it will represented as `('apples', 2)`. " 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "com_fruit = [\n", 23 | " ('grapes', 1), ('oranges', 2), ('grapes', 3), ('oranges', 4), ('kiwis', 1),\n", 24 | " ('blueberries', 10), ('kiwis', 7), ('oranges', 9), ('cherries', 6), ('lemon', 3),\n", 25 | " ('grapes', 13), ('oranges', 1), ('grapes', 5), ('oranges', 8), ('kiwis', 6),\n", 26 | " ('blueberries', 1), ('kiwis', 5), ('oranges', 7), ('cherries', 1), ('lemon', 4),\n", 27 | "]" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "We want to collectively count how much fruit we have. Create a function `collect_fruit()` that:\n", 35 | "- takes `fruit_lst` as a required argument\n", 36 | "- assumes the `fruit_lst` argument has the same format as `com_fruit`\n", 37 | "- returns a `defaultdict` with fruit names as keys and fruit counts as values\n", 38 | "\n", 39 | "Test your function by calling\n", 40 | "```python\n", 41 | "com_fruit_ddict = collect_fruit(com_fruit)\n", 42 | "```\n", 43 | "and printing `com_fruit_ddict`." 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "# TODO: insert solution here" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## ** Exercise**\n", 60 | "\n", 61 | "Now that we have `com_fruit_ddict`, we want to be able to quickly find if a certain fruit is in our `defaultdict`.\n", 62 | "\n", 63 | "Create a function `find_fruit()` that:\n", 64 | "- takes a required argument `fruit_ddict` and the fruit you want to find `fruit` as a string\n", 65 | "- assumes the `fruit_ddict` argument has the same format as `com_fruit_ddict`\n", 66 | "- let the user know how much `fruit` we have and update that `fruit` with a val of 0 if it does not exist\n", 67 | "- return the potentially updated `fruit_ddict`\n", 68 | "\n", 69 | "Tetst your function by calling\n", 70 | "```python\n", 71 | "com_fruit_ddict = find_fruit(com_fruit_ddict, 'apples')\n", 72 | "```\n", 73 | "and printing `com_fruit_ddict`." 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "# TODO: insert solution here" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": {}, 88 | "source": [ 89 | "## ** Exercise**\n", 90 | "\n", 91 | "Now that we are able to let the user know how much fruit we have, we want to sort `com_fruit_ddict` by value.\n", 92 | "\n", 93 | "Create a function `sort_fruit_ddict()` that:\n", 94 | "- takes a required argument `fruit_ddict` and assumes it is the same format as `com_fruit_ddict`\n", 95 | "- returns an `OrderedDict` sorted in decreasing order of fruit counts\n", 96 | "\n", 97 | "Test your function by calling\n", 98 | "```python\n", 99 | "com_fruit_odict = sort_fruit_ddict(com_fruit_ddict)\n", 100 | "```\n", 101 | "and printing `com_fruit_odict`." 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "metadata": {}, 108 | "outputs": [], 109 | "source": [ 110 | "# TODO: insert solution here" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "## ** Exercise**\n", 118 | "\n", 119 | "Ashley, Andras, and Matt will be attending the BBQ but can't figure out which seating order they would like to sit in! You must show them all the possiblities of ordered seating so they can make a choice.\n", 120 | "\n", 121 | "Oh no, the `itertools` module is crawling with bugs and is down for maintenance! Create a function `man_three_permutations()` that:\n", 122 | "\n", 123 | "- takes `lst` as a required argument that represents the list of names you will permutate\n", 124 | "- assumes `lst` only has 3 elements \n", 125 | "- manually computes the r=3 permutations of `lst`\n", 126 | "- returns a list of tuples where each tuple is a possible permutation\n", 127 | "\n", 128 | "Test your function by printing each permutation from the call `man_three_permutations(bbq_names)`." 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "bbq_names = ['Matt', 'Andras', 'Ashley']" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "# TODO: insert solution here" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "Oh great, `itertools` is back online! Create function `three_permutations()` that:\n", 154 | "- takes `lst` as a required argument that represents the list of names you will permutate\n", 155 | "- assumes `lst` only has 3 elements\n", 156 | "- returns a list of 3-tuple permutations where each tuple is a possible permutation\n", 157 | "- utilizes `permutations` from `itertools`" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "# TODO: insert solution here" 167 | ] 168 | } 169 | ], 170 | "metadata": { 171 | "kernelspec": { 172 | "display_name": "Python 3", 173 | "language": "python", 174 | "name": "python3" 175 | }, 176 | "language_info": { 177 | "codemirror_mode": { 178 | "name": "ipython", 179 | "version": 3 180 | }, 181 | "file_extension": ".py", 182 | "mimetype": "text/x-python", 183 | "name": "python", 184 | "nbconvert_exporter": "python", 185 | "pygments_lexer": "ipython3", 186 | "version": "3.8.8" 187 | } 188 | }, 189 | "nbformat": 4, 190 | "nbformat_minor": 4 191 | } 192 | -------------------------------------------------------------------------------- /week_3/day_2_assets/bbq_event-DictWriter.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Matt,0,yes 3 | Andras,10,no 4 | Ashley,5,yes 5 | -------------------------------------------------------------------------------- /week_3/day_2_assets/bbq_event.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Matt,0,yes 3 | Andras,10,no 4 | Ashley,5,yes 5 | -------------------------------------------------------------------------------- /week_3/day_2_assets/bbq_event.json: -------------------------------------------------------------------------------- 1 | {"entry1": {"name": "Matt", "num_guests": 0, "paid": true}, "entry2": {"name": "Andras", "num_guests": 10, "paid": false}, "entry3": {"name": "Ashley", "num_guests": 5, "paid": true}} -------------------------------------------------------------------------------- /week_3/day_2_assets/bbq_event.txt: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Matt,0,yes 3 | Andras,10,no 4 | Ashley,5,yes 5 | -------------------------------------------------------------------------------- /week_3/day_2_assets/incorrect_cols.csv: -------------------------------------------------------------------------------- 1 | col1,col2 2 | row1_1,row1_2,row1_3 3 | -------------------------------------------------------------------------------- /week_3/day_2_assets/incorrect_cols.txt: -------------------------------------------------------------------------------- 1 | col1,col2 2 | row1_1,row1_2,row1_3 3 | -------------------------------------------------------------------------------- /week_3/day_2_assets/incorrect_row_entry.csv: -------------------------------------------------------------------------------- 1 | col1,col2,col2 2 | row1_1,row1_2 3 | -------------------------------------------------------------------------------- /week_3/day_2_assets/incorrect_row_entry.txt: -------------------------------------------------------------------------------- 1 | col1,col2,col3 2 | row1_1,row1_2 3 | -------------------------------------------------------------------------------- /week_3/day_2_assets/lab/pulled_pork_recipe.txt: -------------------------------------------------------------------------------- 1 | YIELDS: 6-8 2 | PREP TIME: 10 mins 3 | TOTAL TIME: 3 hrs 20 mins 4 | 5 | INGREDIENTS (FOR PORK) 6 | 4 lb. boneless pork shoulder 7 | 3 tbsp. packed brown sugar 8 | 1 tbsp. kosher salt 9 | 1 tbsp. smoked paprika 10 | 1 tsp. garlic powder 11 | 1 tsp. onion powder 12 | 1 tsp. ground cumin 13 | Freshly ground black pepper 14 | 2 tbsp. vegetable oil 15 | 12 oz. lager 16 | 17 | INGREDIENTS (FOR THE BARBECUE SAUCE + SANDWICHES) 18 | 1 1/2 c. ketchup 19 | 1/3 c. apple cider vinegar 20 | 1/2 c. Dijon mustard 21 | 1/4 c. brown sugar 22 | 2 tbsp. Worcestershire sauce 23 | Buns, for serving 24 | 25 | DIRECTIONS 26 | 1. Make pork: Preheat oven to 300°. Trim excess fat from pork and cut into large pieces to fit in a large Dutch oven. 27 | 28 | 2. In a small bowl, combine brown sugar, salt, paprika, garlic powder, onion powder, and cumin, then season with black pepper. Rub all over pork. (This can be done the night before.) 29 | 30 | 3. In a large Dutch oven over medium high heat, heat oil. Working in batches, add pork and sear on all sides. (Spices can burn quickly so don’t let it go for too long!) 31 | 32 | 4. Pour beer around pork and cover with lid. Transfer to oven and cook until pork is beginning to turn tender, about 3 hours. Remove lid and cook until pork is very tender and pulls apart easily with a fork, 1 to 2 hours more. 33 | 34 | 5. Remove pork from Dutch oven and let rest while you prepare barbecue sauce. 35 | 36 | 6. Make barbecue sauce: To the pan drippings in the Dutch oven, whisk in ketchup, apple cider vinegar, mustard, brown sugar and Worcestershire. Over medium-high heat, bring mixture to a boil. Reduce heat, and simmer until thickened slightly, about 5 minutes. 37 | 38 | 7. Shred pork using two forks. Toss shredded meat with about half the barbecue sauce. 39 | 40 | 8. Serve warm with buns and more barbecue sauce. 41 | 42 | REFERENCES 43 | - https://www.delish.com/cooking/recipe-ideas/recipes/a58254/best-pulled-pork-recipe/ -------------------------------------------------------------------------------- /week_3/day_2_assets/test.txt: -------------------------------------------------------------------------------- 1 | This is the first line of the file. 2 | Second line of the file. -------------------------------------------------------------------------------- /week_3/day_2_assets/tuple_test.txt: -------------------------------------------------------------------------------- 1 | ('number of people', 1239) -------------------------------------------------------------------------------- /week_3/day_2_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "## ** Exercise**\n", 12 | "\n", 13 | "Let's do some planning for the Community BBQ! You are in charge of managing the recipes used for the event. We have a pulled pork recipe located at `day_2_assets/lab/pulled_pork_recipe.txt` relative to where this notebook is located.\n", 14 | "\n", 15 | "Creates a function `read_recipe()` that:\n", 16 | "- takes a required argument `recipe_filepath` that is a string of where the recipe is located\n", 17 | "- returns the recipe contents as one large string\n", 18 | "\n", 19 | "Afterwards, pass in the pulled pork recipe path to `read_recipe()`, save the output to a variable name `read_recipe_str` and print the output." 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "# TODO: insert solution here" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "## ** Exercise**\n", 36 | "\n", 37 | "Great! Now that you have the pulled pork recipe, we want to scale it to feed all the people attending the BBQ. So far, 20 people have signed up to attend. We want to scale the recipe such that the minimum number it yields just barely exceeds the number of people that are attending. To help you out, I've created a dictionary, `recipe_num_dict`, that has a nickname for scalable entries as keys and a string that represents the values that need to be scaled as values to the dictionary. Although not all recipes' preperation and total times scale proportionally when increasing the ingredients, let's assume ours does." 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "recipe_num_dict = {\n", 47 | " 'num_yields': '6-8',\n", 48 | " 'num_prep': '10 mins',\n", 49 | " 'num_total': '210 mins',\n", 50 | " 'pork_boneless': '4 lb.',\n", 51 | " 'pork_sugar': '3 tbsp.',\n", 52 | " 'pork_salt': '1 tbsp.',\n", 53 | " 'pork_paprika': '1 tbsp.',\n", 54 | " 'pork_garlic_pow': '1 tsp.',\n", 55 | " 'pork_onion_pow': '1 tsp.',\n", 56 | " 'pork_cumin': '1 tsp.',\n", 57 | " 'pork_veg_oil': '2 tbsp.',\n", 58 | " 'pork_lager': '12 oz.',\n", 59 | " 'sauce_ketchup': '1.5 c.',\n", 60 | " 'sauce_vinegar': '0.33 c.',\n", 61 | " 'sauce_mustard': '0.5 c.',\n", 62 | " 'sauce_sugar': '0.25 c.',\n", 63 | " 'sauce_worcestershire': '2 tbsp.'\n", 64 | "}" 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "Create a function, `scale_recipe()` that:\n", 72 | "- takes required arguments:\n", 73 | " - `nickname_entry_dict`: dictionary that contains the nickname and entry key-value pairs\n", 74 | " - `scale`: scalable multiplier for your recipe\n", 75 | "- assume `scale` is a float if 0 < `scale` < 1; otherwise, it is an integer\n", 76 | "- returns an updated nickname and entry key-value pair dictionary where the entry value is scaled\n", 77 | "\n", 78 | "Feel free to create additional functions to help with the parsing.\n", 79 | "\n", 80 | "Then, save the scaled recipe to `scaled_recipe_num_dict` and display the scaled dictionary." 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "# TODO: insert solution here" 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": {}, 95 | "source": [ 96 | "## ** Exercise**\n", 97 | "\n", 98 | "Now that we have scaled the recipe, we want save the scaled values back to a text file.\n", 99 | "\n", 100 | "First we will need to replace the scaled values within the recipe text. I have saved the pulled the pork recipe to `recipe` for convenience. Copy the text in `recipe` to a variable called `recipe_scaled` (leave `recipe` untouched just in case you mess up) and replace the values that were scaled using the `format()` method. Display the scaled recipe and check for any errors." 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": null, 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [ 109 | "recipe = \"\"\"YIELDS: 6-8\n", 110 | "PREP TIME: 10 mins\n", 111 | "TOTAL TIME: 210 mins\n", 112 | "\n", 113 | "INGREDIENTS (FOR PORK)\n", 114 | "4 lb. boneless pork shoulder\n", 115 | "3 tbsp. packed brown sugar\n", 116 | "1 tbsp. kosher salt\n", 117 | "1 tbsp. smoked paprika\n", 118 | "1 tsp. garlic powder\n", 119 | "1 tsp. onion powder\n", 120 | "1 tsp. ground cumin\n", 121 | "Freshly ground black pepper to taste\n", 122 | "2 tbsp. vegetable oil\n", 123 | "12 oz. lager\n", 124 | "\n", 125 | "INGREDIENTS (FOR THE BARBECUE SAUCE + SANDWICHES)\n", 126 | "1.5 c. ketchup\n", 127 | "0.33 c. apple cider vinegar\n", 128 | "0.5 c. Dijon mustard\n", 129 | "0.25 c. brown sugar\n", 130 | "2 tbsp. Worcestershire sauce\n", 131 | "Buns, for serving\n", 132 | "\n", 133 | "DIRECTIONS\n", 134 | "1. Make pork: Preheat oven to 300°. Trim excess fat from pork and cut into large pieces to fit in a large Dutch oven.\n", 135 | "\n", 136 | "2. In a small bowl, combine brown sugar, salt, paprika, garlic powder, onion powder, and cumin, then season with black pepper. Rub all over pork. (This can be done the night before.)\n", 137 | "\n", 138 | "3. In a large Dutch oven over medium high heat, heat oil. Working in batches, add pork and sear on all sides. (Spices can burn quickly so don’t let it go for too long!)\n", 139 | "\n", 140 | "4. Pour beer around pork and cover with lid. Transfer to oven and cook until pork is beginning to turn tender, about 3 hours. Remove lid and cook until pork is very tender and pulls apart easily with a fork, 1 to 2 hours more.\n", 141 | "\n", 142 | "5. Remove pork from Dutch oven and let rest while you prepare barbecue sauce.\n", 143 | "\n", 144 | "6. Make barbecue sauce: To the pan drippings in the Dutch oven, whisk in ketchup, apple cider vinegar, mustard, brown sugar and Worcestershire. Over medium-high heat, bring mixture to a boil. Reduce heat, and simmer until thickened slightly, about 5 minutes.\n", 145 | "\n", 146 | "7. Shred pork using two forks. Toss shredded meat with about half the barbecue sauce.\n", 147 | "\n", 148 | "8. Serve warm with buns and more barbecue sauce.\n", 149 | "\n", 150 | "REFERENCES\n", 151 | "- https://www.delish.com/cooking/recipe-ideas/recipes/a58254/best-pulled-pork-recipe/\n", 152 | "\"\"\"" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "# TODO: insert solution here" 162 | ] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "metadata": {}, 167 | "source": [ 168 | "Now that you have a recipe to feed enough people, let's export the recipe to `day_2_assets/lab/pulled_pork_recipe_scaled.txt`.\n", 169 | "\n", 170 | "Create a function, `write_recipe()`, that:\n", 171 | "- takes required arguments:\n", 172 | " - `recipe_filepath`: string of where the recipe will be written to\n", 173 | " - `recipe_str`: string of the recipe\n", 174 | "\n", 175 | "Afterwards, pass in the location of the scaled pulled pork recipe path and the newly scaled recipe string to `write_recipe()`." 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": {}, 182 | "outputs": [], 183 | "source": [ 184 | "# TODO: insert solution here" 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": {}, 190 | "source": [ 191 | "## ** Exercise**\n", 192 | "\n", 193 | "Ashley from the BBQ Planning Committee had a great idea to put the recipes from the BBQ available on the event webiste! To do this, she needs the recipes in a JSON format stored at `day_2_assets/lab/all_recipes.json`.\n", 194 | "\n", 195 | "Create a function `parse_for_json()` that:\n", 196 | "- takes required arguments:\n", 197 | " - `nickname_entry_dict`: dictionary that contains the nickname and entry key-value pairs\n", 198 | " - `recipe_name`: name of the recipe\n", 199 | "- parses the recipe into JSON format (see example below)\n", 200 | "- returns a dictionary with the `recipe_name` as the key and the JSON formatted recipe as value\n", 201 | "\n", 202 | "Here is an example on how your JSON file should look:\n", 203 | "\n", 204 | "```json\n", 205 | "{\n", 206 | " \"Pulled Pork\": {\n", 207 | " \"yields\": \"24.0-32.0\",\n", 208 | " \"prep time\": \"40.0 mins\",\n", 209 | " \"total time\": \"840.0 mins\",\n", 210 | " \"pork ingredients\": {\n", 211 | " \"pork_boneless\": \"16.0 lb.\",\n", 212 | " \"pork_sugar\": \"12.0 tbsp.\",\n", 213 | " \"pork_salt\": \"4.0 tbsp.\",\n", 214 | " \"pork_paprika\": \"4.0 tbsp.\",\n", 215 | " \"pork_garlic_pow\": \"4.0 tsp.\",\n", 216 | " \"pork_onion_pow\": \"4.0 tsp.\",\n", 217 | " \"pork_cumin\": \"4.0 tsp.\",\n", 218 | " \"pork_veg_oil\": \"8.0 tbsp.\",\n", 219 | " \"pork_lager\": \"48.0 oz.\"\n", 220 | " },\n", 221 | " \"sauce ingredients\": {\n", 222 | " \"sauce_ketchup\": \"6.0 c.\",\n", 223 | " \"sauce_vinegar\": \"1.32 c.\",\n", 224 | " \"sauce_mustard\": \"2.0 c.\",\n", 225 | " \"sauce_sugar\": \"1.0 c.\",\n", 226 | " \"sauce_worcestershire\": \"8.0 tbsp.\"\n", 227 | " },\n", 228 | " \"directions\": {\n", 229 | " \"1\": \"1. Make pork: Preheat oven to 300\\u00b0. Trim excess fat from pork and cut into large pieces to fit in a large Dutch oven.\",\n", 230 | " \"2\": \"2. In a small bowl, combine brown sugar, salt, paprika, garlic powder, onion powder, and cumin, then season with black pepper. Rub all over pork. (This can be done the night before.)\",\n", 231 | " \"3\": \"3. In a large Dutch oven over medium high heat, heat oil. Working in batches, add pork and sear on all sides. (Spices can burn quickly so don\\u2019t let it go for too long!)\",\n", 232 | " \"4\": \"4. Pour beer around pork and cover with lid. Transfer to oven and cook until pork is beginning to turn tender, about 3 hours. Remove lid and cook until pork is very tender and pulls apart easily with a fork, 1 to 2 hours more.\",\n", 233 | " \"5\": \"5. Remove pork from Dutch oven and let rest while you prepare barbecue sauce.\",\n", 234 | " \"6\": \"6. Make barbecue sauce: To the pan drippings in the Dutch oven, whisk in ketchup, apple cider vinegar, mustard, brown sugar and Worcestershire. Over medium-high heat, bring mixture to a boil. Reduce heat, and simmer until thickened slightly, about 5 minutes.\",\n", 235 | " \"7\": \"7. Shred pork using two forks. Toss shredded meat with about half the barbecue sauce.\",\n", 236 | " \"8\": \"8. Serve warm with buns and more barbecue sauce.\"\n", 237 | " }\n", 238 | " }\n", 239 | "}\n", 240 | "```\n", 241 | "\n", 242 | "Lastly, create a function, `dict_to_json()`, that:\n", 243 | "- takes required arguments:\n", 244 | " - `filepath`: path to save JSON file to\n", 245 | " - `json_dict`: dictionary to export to JSON\n", 246 | "- exports `json_dict` to JSON at `filepath`" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "# TODO: insert solution here" 256 | ] 257 | } 258 | ], 259 | "metadata": { 260 | "kernelspec": { 261 | "display_name": "Python 3", 262 | "language": "python", 263 | "name": "python3" 264 | }, 265 | "language_info": { 266 | "codemirror_mode": { 267 | "name": "ipython", 268 | "version": 3 269 | }, 270 | "file_extension": ".py", 271 | "mimetype": "text/x-python", 272 | "name": "python", 273 | "nbconvert_exporter": "python", 274 | "pygments_lexer": "ipython3", 275 | "version": "3.8.8" 276 | } 277 | }, 278 | "nbformat": 4, 279 | "nbformat_minor": 4 280 | } 281 | -------------------------------------------------------------------------------- /week_3/day_3_assets/bbq_notification.txt: -------------------------------------------------------------------------------- 1 | This summer there will be a BBQ! -------------------------------------------------------------------------------- /week_3/day_3_assets/event_tables/bbq_event_1.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Matt,0,yes 3 | Andras,10,no 4 | Ashley,5,yes 5 | -------------------------------------------------------------------------------- /week_3/day_3_assets/event_tables/bbq_event_2.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Lauren,3,yes 3 | Ryan,0,no 4 | Callie,6,yes 5 | -------------------------------------------------------------------------------- /week_3/day_3_assets/lab.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_3/day_3_assets/lab.zip -------------------------------------------------------------------------------- /week_3/day_3_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "16dbd229-3c85-4a9b-9231-a102870dda4f", 6 | "metadata": {}, 7 | "source": [ 8 | "#
LAB
\n", 9 | "\n", 10 | "---\n", 11 | "\n", 12 | "## ** Exercise**\n", 13 | "\n", 14 | "Welcome the BBQ scavenger hunt! For the initial setup, uncompress `day_3_assets/lab.zip` at `day_3_assets/lab`. Your search will start at `day_3_assets/lab` and you will explore its sub-directories to find coins! To start your hunt, simply change directories to either `walk_north`, `walk_south`, `walk_east`, or `walk_west`.\n", 15 | "\n", 16 | "To navigate to another directory, you must read and do what the `README.txt` file states before moving further (note, not all directories have a `README.txt` file). Some files will require you to solve an exercise before advancing. To do so, simply insert your solutions below. If you navigate back to a directory where you've already solved an exercise, you don't have to solve it again. If a file tells you to roll a `n`-sided dice, use the `roll_dice(n)` function below.\n", 17 | "\n", 18 | "Each coin has a point value and there are a total of 30 points in this scavenger hunt. Can you find them all?\n", 19 | "\n", 20 | "Some additional rules:\n", 21 | "- you MAY use any tools you've learned so far EXCEPT:\n", 22 | " - any tools to list directory trees beyond the current working directory\n", 23 | " - any tools to find files outside the current working directory\n", 24 | "- you MAY NOT use any type of directory navigation GUIs (e.g., Finder on Mac OS or File Explorer on Windows)\n", 25 | "- ignore any hidden directories or files (i.e., starts with `.`)\n", 26 | "\n", 27 | "Helpful hints:\n", 28 | "- feel free to create helper functions that will assist you on your journey!\n", 29 | " - e.g., you will frequently change directories, print the current directory, list files, and read text files so it might be useful to create a function that combines them as one action\n", 30 | "- it may be helpful to create a starting path using the `pathlib` module then create and update a seperate path variable for each direction you branch off in\n", 31 | " - e.g., if `start_path = Path.cwd() / 'day_3_assets' / 'lab'` is our starting path and I want to go to `walk_north`, you could create a variable `north_path = start_path / 'walk_north'` where each time you change directories going north, you update `north_path`\n", 32 | "\n", 33 | "Good luck!" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 1, 39 | "id": "b3ba3584-d6b3-4a97-bc1f-1b7a2672d42b", 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "3\n" 47 | ] 48 | } 49 | ], 50 | "source": [ 51 | "from random import randint\n", 52 | "\n", 53 | "def roll_dice(num_sides):\n", 54 | " return randint(1, num_sides)\n", 55 | "\n", 56 | "# e.g., roll a 3-sided dice\n", 57 | "print(roll_dice(3))" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "id": "67143e81-f61f-4672-bede-6dbcc08195d7", 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "# TODO: insert solutions here" 68 | ] 69 | } 70 | ], 71 | "metadata": { 72 | "kernelspec": { 73 | "display_name": "Python 3", 74 | "language": "python", 75 | "name": "python3" 76 | }, 77 | "language_info": { 78 | "codemirror_mode": { 79 | "name": "ipython", 80 | "version": 3 81 | }, 82 | "file_extension": ".py", 83 | "mimetype": "text/x-python", 84 | "name": "python", 85 | "nbconvert_exporter": "python", 86 | "pygments_lexer": "ipython3", 87 | "version": "3.8.8" 88 | } 89 | }, 90 | "nbformat": 4, 91 | "nbformat_minor": 5 92 | } 93 | -------------------------------------------------------------------------------- /week_3/day_4_assets/def_sqrt.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_3/day_4_assets/def_sqrt.pkl -------------------------------------------------------------------------------- /week_3/day_4_assets/event_tables.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_3/day_4_assets/event_tables.zip -------------------------------------------------------------------------------- /week_3/day_4_assets/event_tables/bbq_event_1.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Matt,0,yes 3 | Andras,10,no 4 | Ashley,5,yes 5 | -------------------------------------------------------------------------------- /week_3/day_4_assets/event_tables/bbq_event_2.csv: -------------------------------------------------------------------------------- 1 | name,num_guests,paid 2 | Lauren,3,yes 3 | Ryan,0,no 4 | Callie,6,yes 5 | -------------------------------------------------------------------------------- /week_3/day_4_assets/lab/bbq_date_str.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_3/day_4_assets/lab/bbq_date_str.pkl -------------------------------------------------------------------------------- /week_3/day_4_assets/lab/output.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brown-ccv/workshop-python-2021/42b9df97dd05c60be9efbf9b971cb5e8635083ec/week_3/day_4_assets/lab/output.pkl -------------------------------------------------------------------------------- /week_3/day_4_assets/recipes/cornbread_recipe.txt: -------------------------------------------------------------------------------- 1 | YIELDS: 8-10 2 | PREP TIME: 25 mins 3 | TOTAL TIME: 1 hr 10 mins 4 | 5 | INGREDIENTS (CORNBREAD) 6 | 1 tablespoon butter, for greasing the pan, plus 1 1/2 cups butter, melted 7 | 3/4 pound left over BBQ pork or beef 8 | 1 1/2 cups white sugar 9 | 6 eggs 10 | 1/4 cup plus 2 tablespoons milk 11 | 1 1/2 (15-ounce) cans cream-style corn 12 | 1/4 cup drained canned chopped green chile peppers 13 | 1 1/2 cups shredded cheese (Recommended: combination Monterey Jack and Cheddar) 14 | 1 1/2 cups all-purpose flour 15 | 1 1/2 cups yellow cornmeal 16 | 2 tablespoons baking powder 17 | Pinch salt 18 | 19 | INGREDIENTS (TOPPING) 20 | 6 tablespoons butter 21 | 3 tablespoons your favorite bbq sauce 22 | 1 1/2 tablespoons cayenne pepper 23 | 1 1/2 tablespoons garlic powder 24 | 25 | DIRECTIONS 26 | 1. Preheat oven to 325 degrees F. 27 | 28 | 2. Lightly butter a deep 9 by 13-inch baking dish. 29 | 30 | 3. Shred left over BBQ into fine pieces and set aside. 31 | 32 | 4. In a large bowl, stir together the butter, milk, and sugar. Beat in the eggs, 1 at a time, until well incorporated. Add the creamed corn, chiles, cheese, and shredded BBQ and stir until well incorporated. 33 | 34 | 5. In a separate bowl, stir together flour, cornmeal, baking powder, and salt. Add flour mixture to corn mixture; stir until smooth. Pour batter into prepared pan. 35 | 36 | 6. Bake in preheated oven for 1 hour 10 minutes, or until golden brown and until a toothpick inserted into center of the pan comes out clean. 37 | 38 | 7. Topping: Combine all and melt in microwave. Brush over cornbread and place back in oven for a few minutes. Cut into squares and serve warm. It's ok to break up pieces and serve in a small bowl. 39 | 40 | REFERENCES 41 | - https://www.foodnetwork.com/recipes/kents-bbq-cornbread-recipe-1953148 -------------------------------------------------------------------------------- /week_3/day_4_assets/recipes/pulled_pork_recipe.txt: -------------------------------------------------------------------------------- 1 | YIELDS: 6-8 2 | PREP TIME: 10 mins 3 | TOTAL TIME: 3 hrs 20 mins 4 | 5 | INGREDIENTS (FOR PORK) 6 | 4 lb. boneless pork shoulder 7 | 3 tbsp. packed brown sugar 8 | 1 tbsp. kosher salt 9 | 1 tbsp. smoked paprika 10 | 1 tsp. garlic powder 11 | 1 tsp. onion powder 12 | 1 tsp. ground cumin 13 | Freshly ground black pepper 14 | 2 tbsp. vegetable oil 15 | 12 oz. lager 16 | 17 | INGREDIENTS (FOR THE BARBECUE SAUCE + SANDWICHES) 18 | 1 1/2 c. ketchup 19 | 1/3 c. apple cider vinegar 20 | 1/2 c. Dijon mustard 21 | 1/4 c. brown sugar 22 | 2 tbsp. Worcestershire sauce 23 | Buns, for serving 24 | 25 | DIRECTIONS 26 | 1. Make pork: Preheat oven to 300°. Trim excess fat from pork and cut into large pieces to fit in a large Dutch oven. 27 | 28 | 2. In a small bowl, combine brown sugar, salt, paprika, garlic powder, onion powder, and cumin, then season with black pepper. Rub all over pork. (This can be done the night before.) 29 | 30 | 3. In a large Dutch oven over medium high heat, heat oil. Working in batches, add pork and sear on all sides. (Spices can burn quickly so don’t let it go for too long!) 31 | 32 | 4. Pour beer around pork and cover with lid. Transfer to oven and cook until pork is beginning to turn tender, about 3 hours. Remove lid and cook until pork is very tender and pulls apart easily with a fork, 1 to 2 hours more. 33 | 34 | 5. Remove pork from Dutch oven and let rest while you prepare barbecue sauce. 35 | 36 | 6. Make barbecue sauce: To the pan drippings in the Dutch oven, whisk in ketchup, apple cider vinegar, mustard, brown sugar and Worcestershire. Over medium-high heat, bring mixture to a boil. Reduce heat, and simmer until thickened slightly, about 5 minutes. 37 | 38 | 7. Shred pork using two forks. Toss shredded meat with about half the barbecue sauce. 39 | 40 | 8. Serve warm with buns and more barbecue sauce. 41 | 42 | REFERENCES 43 | - https://www.delish.com/cooking/recipe-ideas/recipes/a58254/best-pulled-pork-recipe/ -------------------------------------------------------------------------------- /week_3/day_4_assets/recipes/smoked_mac_and_cheese_recipe.txt: -------------------------------------------------------------------------------- 1 | YIELDS: 10 2 | PREP TIME: 20 mins 3 | TOTAL TIME: 40 mins 4 | 5 | INGREDIENTS (MAC AND CHEESE) 6 | 1/4 cup unsalted butter 7 | 1/4 cup all-purpose flour 8 | 2 cups milk 9 | 2 cups grated sharp cheddar 10 | 2 cups grated Colby cheese 11 | 1 teaspoon Morton coarse kosher salt 12 | 1/2 teaspoon ground black pepper 13 | 1 pound elbow macaroni 14 | 1 teaspoon finely chopped parsley (optional) 15 | 16 | INGREDIENTS (TOPPING) 17 | 1 cup Panko bread crumbs 18 | 3 tablespoons butter, melted 19 | 20 | DIRECTIONS 21 | 1. Boil the mac. Cook the elbow macaroni according to instructions, preferably al dente (tender but firm). 22 | 23 | 2. Make the sauce. Melt the butter in a large saucepan over medium heat. Add the flour to the butter and whisk until smooth. Slowly add the milk, stirring constantly until fully incorporated. 24 | 25 | 3. Reduce the heat to low and add the cheese, salt, and pepper to the saucepan. Continue to stir the mixture until the cheese has melted. Add the cooked pasta to the saucepan and stir until the pasta is completely coated with the cheese sauce. Remove from the heat. 26 | 27 | 4. Prep the topping. In a small bowl, toss the Panko breadcrumbs with the melted butter. 28 | 29 | 5. Assemble. Coat the inside of a 3-quart casserole dish with non-stick cooking spray. Pour the mac-and-cheese into the casserole dish and spread it out evenly. Top the mac-and-cheese with the Panko breadcrumbs. 30 | 31 | 6. Fire up. Prepare a grill for direct cooking by evenly spreading a chimney full of pre-heated charcoal briquets across the grill’s charcoal grate. Add 2 to 3 chunks of your favorite smoking wood to the charcoal for flavor. Adjust the grill vents to bring the temperature to about 350°F. On a gas grill, adjust the temperature knobs to maintain a temperature of approximately 350°F. Add wood to the gas grill according to our recommendations here. 32 | 33 | 7. Cook. Set the casserole dish in the center of the grill’s main cooking grate. Cover the grill. 34 | 35 | 8. Allow the mac-and-cheese to smoke until bubbly and golden brown, approximately 40 minutes. 36 | 37 | 9. Serve. Remove the smoked mac-and-cheese from the grill. Garnish with chopped parsley (optional) and serve immediately. 38 | 39 | REFERENCES 40 | - https://amazingribs.com/tested-recipes/other-fun-food-recipes/smoked-mac-and-cheese-recipe/ -------------------------------------------------------------------------------- /week_3/day_4_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "#
LAB
\n", 8 | "\n", 9 | "---\n", 10 | "\n", 11 | "## ** Exercise**\n", 12 | "\n", 13 | "With an influx of people registering for the Community BBQ, we want to make sure the email addresses they enter into the registration form is valid. We will use regexes to do this.\n", 14 | "\n", 15 | "Let's break down the regex string you will be creating in a bit that will contain a pattern for valid email address. We will use the email address, `example@gmail.com`, as an example. We want our pattern to:\n", 16 | "1. match every character from the beginning of the string up until the `@` character. For example, our pattern should match `example@` from our email address.\n", 17 | "2. match ever character *except* \".\". For example, our pattern should match `gmail` from our email address.\n", 18 | "3. match the domain characters (with a min length of 2 and a max length of 10 characters) until the end of the string. For example, our pattern should match `.com` from our email address.\n", 19 | "\n", 20 | "Your pattern will combine the attributes above sequentially as one regex pattern.\n", 21 | "\n", 22 | "HINTs: if you are having trouble, here are some helpful hints that map to the above attributes of your pattern:\n", 23 | "1. this pattern will use the `^`, `.`, `+`, and `@` characters\n", 24 | "2. this pattern will use the `[`, `^`, `.`, `]`, `.`, and `*` characters\n", 25 | "3. this pattern will use the `\\`, `.`, `[a-z]`, `{2,10}`, and `$` characters\n", 26 | "\n", 27 | "Then, create a function, `check_email_address()`, that:\n", 28 | "- takes required argument `email` that is a string of an email address\n", 29 | "- compiles your one regex pattern using `flags=re.IGNORECASE` as an argument to ignore case\n", 30 | "- if the pattern matches the email address, print a message saying that it's valid; otherwise, print a message saying it's not valid" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "# TODO: insert solution here" 40 | ] 41 | }, 42 | { 43 | "cell_type": "markdown", 44 | "metadata": {}, 45 | "source": [ 46 | "## ** Exercise**\n", 47 | "\n", 48 | "Now you have enough information to start working on a countdown clock for this year's Community BBQ since the 2020 event was cancelled for COVID reasons.\n", 49 | "\n", 50 | "The next BBQ in 2021 will start on July 17, 2021 in Providence, RI at 10am.\n", 51 | "\n", 52 | "Do the following:\n", 53 | "- create a `datetime` instance from the `datetime` module with the above times and dates named `bbq_date`\n", 54 | "- create a `datetime` instance from the `datetime` module of the time and date of now named `now`\n", 55 | "- compute the difference between `now` and `bbq_date` named `countdown`\n", 56 | "- print `\"Countdown to Community BBQ 2021:\"` followed by `countdown`\n", 57 | "\n", 58 | "Taking the difference between two `datetime` instances returns a `datetime.timedelta` instance, which is your `countdown` variable!" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "# TODO: insert solution here" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": {}, 73 | "source": [ 74 | "Now that you know how to add time zone information to a Python `datetime` instance, you can improve your Community BBQ countdown code. \n", 75 | "\n", 76 | "Here in Providence, RI the time zone is `\"America/New_York\"`.\n", 77 | "\n", 78 | "Do the following:\n", 79 | "- create `bbq_date` as above but with passing the correct time zone to the `tzinfo` argument.\n", 80 | "- create `now` as above but with the correct time zone\n", 81 | "- compute the difference between `now` and `bbq_date` named `countdown`\n", 82 | "- print `\"Countdown to Community BBQ 2021:\"` followed by `countdown` and the name of the time zone" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "# TODO: insert solution here" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "With the subtraction operator, your `timedelta` object couldn’t count intervals of time larger than a day. However, `relativedelta` allows you to show the years, months, and days remaining.\n", 99 | "\n", 100 | "Do the following:\n", 101 | "- replace the plain substraction operator with `relativedelta` and save the output to `countdown`\n", 102 | "- print `\"Countdown to Community BBQ 2021:\"` followed by `countdown` and the name of the time zone" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "# TODO: insert solution here" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "This output tells us each individual time unit of when the Community BBQ will happen but it isn't very pretty. Let's fix that.\n", 119 | "\n", 120 | "Recall, the built-in function\n", 121 | "```python\n", 122 | "getattr(obj, name)\n", 123 | "```\n", 124 | "returns the value of the named attribute of `obj` where `name` is a string. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. \n", 125 | "\n", 126 | "First, we will create a function, `time_amount()`, that:\n", 127 | "- takes required arguments:\n", 128 | " - `time_unit`: time unit string\n", 129 | " - `countdown`: `relativedelta` instance\n", 130 | "- gets the value from `countdown` from named attribute `time_unit`\n", 131 | "- returns the time attribute value with the `time_unit` as one string\n", 132 | "\n", 133 | "The time units we care about are years, months, days, hours, minutes, and seconds.\n", 134 | "\n", 135 | "Then, do the following:\n", 136 | "- for each time unit, use `time_amount()` to create a list of time value and time unit strings\n", 137 | "- print `\"Countdown to Community BBQ 2021:\"` followed by joining each time value and the name of the time zone" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "# TODO: insert solution here" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "In lecture, you learned about creating `datetime` instances using `.strptime()`. This method uses a special mini-language within Python to specify how the date string is formatted.\n", 154 | "\n", 155 | "Python datetime has an additional method called \n", 156 | "```python\n", 157 | ".strftime(format_str)\n", 158 | "```\n", 159 | "that allows you to format a datetime instance to a string. In a sense, it’s the reverse operation of parsing using `.strptime()`. You can differentiate between the two methods by remembering that the `p` in `.strptime()` stands for **parse**, and the `f` in `.strftime()` stands for **format**.\n", 160 | "\n", 161 | "In your Community BBQ countdown, you can use `.strftime()` to print output to let the user know the date on which the Community BBQ will start. You can find the formatting codes that you want to use [here](https://strftime.org/).\n", 162 | "\n", 163 | "Here is the desired date format for the Community BBQ: `Saturday, July 17, 2021 at 10:00 AM EDT`\n", 164 | "\n", 165 | "Do the following:\n", 166 | "- use `.strftime` to retrieve the desired date format above\n", 167 | "- print `\"Community BBQ 2021 will start on:\"` then the retrieved date format retrieved\n", 168 | "- print `\"Countdown to Community BBQ 2021:\"` followed by joining each time value" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "# TODO: insert solution here" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "metadata": {}, 183 | "source": [ 184 | "## ** Exercise**\n", 185 | "\n", 186 | "Now that we have a countdown timer till the next Community BBQ, we can share it with everyone to get people extra excited for the gathering! To do this, we will pickle a few objects we've created and store our objects at `day_4_assets/lab`.\n", 187 | "\n", 188 | "First, create `bbq_pickle_dict` that is a dictionary of string variable names as keys with picklable objects as values. Insert the following into `bbq_pickle_dict`:\n", 189 | "- the Community BBQ start date variable you created\n", 190 | "- the output of each time value of the countdown\n", 191 | "\n", 192 | "Then, create a function, `serialize_objs()` that:\n", 193 | "- takes required arguments:\n", 194 | " - `pickle_dict`: dictionary of string variable names as keys with picklable objects as values\n", 195 | " - `path`: where to store the pickled objects\n", 196 | "- pickles each item in `pickle_dict`\n", 197 | "- prints a message to the user that the file was pickled along with the path to the pickled object\n", 198 | "\n", 199 | "Test `serialize_objs()` by passing in `bbq_pickle_dict` and the correct storage location. " 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "# TODO: insert solution here" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "To verify that we pickled our objects successfully, we will unpickle what you just pickled and output them to the console.\n", 216 | "\n", 217 | "Create a function, `deserialize_objs()`, that:\n", 218 | "- takes required arugment `unpickle_lst` that is a list of paths to unpickle\n", 219 | "- returns a dictionary of string variable names as keys with picklable objects as values\n", 220 | "\n", 221 | "Test `deserialize_objs()` by passing in a list of pickled paths, print out the results, and verify that your unpickled objects are the same as your previously pickled objects." 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "# TODO: insert solution here" 231 | ] 232 | } 233 | ], 234 | "metadata": { 235 | "kernelspec": { 236 | "display_name": "Python 3", 237 | "language": "python", 238 | "name": "python3" 239 | }, 240 | "language_info": { 241 | "codemirror_mode": { 242 | "name": "ipython", 243 | "version": 3 244 | }, 245 | "file_extension": ".py", 246 | "mimetype": "text/x-python", 247 | "name": "python", 248 | "nbconvert_exporter": "python", 249 | "pygments_lexer": "ipython3", 250 | "version": "3.8.8" 251 | } 252 | }, 253 | "nbformat": 4, 254 | "nbformat_minor": 4 255 | } 256 | -------------------------------------------------------------------------------- /week_4/data/people.csv: -------------------------------------------------------------------------------- 1 | ,name,age,birthplace,is_singer 2 | 0,Ashley,30,USA,False 3 | 1,Andras,36,Hungary,False 4 | 2,Rihanna,28,Barbados,True 5 | 3,Emily,33,USA,False 6 | -------------------------------------------------------------------------------- /week_4/data/weather.csv: -------------------------------------------------------------------------------- 1 | Today,Sunny,High: 62 °F,"Today: Sunny, with a high near 62. East wind 11 to 14 mph, with gusts as high as 30 mph. " 2 | Tonight,Partly Cloudy,Low: 41 °F,"Tonight: Partly cloudy, with a low around 41. Northeast wind 6 to 8 mph. " 3 | Wednesday,Sunny,High: 63 °F,"Wednesday: Sunny, with a high near 63. East wind 7 to 9 mph. " 4 | WednesdayNight,Mostly Clear,Low: 40 °F,"Wednesday Night: Mostly clear, with a low around 40. East wind around 6 mph becoming calm after midnight. " 5 | Thursday,Sunny,High: 68 °F,"Thursday: Sunny, with a high near 68. Calm wind becoming south 5 to 7 mph in the afternoon. " 6 | ThursdayNight,Mostly Clear,Low: 47 °F,"Thursday Night: Mostly clear, with a low around 47. Southwest wind around 6 mph. " 7 | Friday,Sunny,High: 78 °F,"Friday: Sunny, with a high near 78. Southwest wind 5 to 8 mph. " 8 | FridayNight,Partly Cloudy,Low: 56 °F,"Friday Night: Partly cloudy, with a low around 56. Southwest wind 3 to 7 mph. " 9 | Saturday,Mostly Sunny,High: 70 °F,"Saturday: Mostly sunny, with a high near 70. Light north wind becoming east 5 to 10 mph in the morning. " -------------------------------------------------------------------------------- /week_4/day_1_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Problem 1\n", 8 | "Read in the imdb.csv file from the `data` folder. It contains info on movies released in 2019.\n" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "## Problem 2\n", 23 | "Answer the following questions:" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "2.1 Which movie(s) in the imdb file has the highest rating?" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "2.2 How many movies received at least 1000 votes?" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "2.3 How many movies received at least 1000 votes and a rating of at least 9.0? What are the titles of these movies?" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": {}, 71 | "source": [ 72 | "# Problem 3\n", 73 | "\n", 74 | "Read in the adult dataset and answer the following questions." 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "1. How many females have a capital gain of at least $1000?" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "2. How many germans are in the dataset? And how many of them earn more than 50k?" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": {}, 115 | "source": [ 116 | "3. What percentage of people earn more than 50k in the local, state, or federal government? " 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": null, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [] 132 | } 133 | ], 134 | "metadata": { 135 | "kernelspec": { 136 | "display_name": "Python 3", 137 | "language": "python", 138 | "name": "python3" 139 | }, 140 | "language_info": { 141 | "codemirror_mode": { 142 | "name": "ipython", 143 | "version": 3 144 | }, 145 | "file_extension": ".py", 146 | "mimetype": "text/x-python", 147 | "name": "python", 148 | "nbconvert_exporter": "python", 149 | "pygments_lexer": "ipython3", 150 | "version": "3.8.8" 151 | } 152 | }, 153 | "nbformat": 4, 154 | "nbformat_minor": 4 155 | } 156 | -------------------------------------------------------------------------------- /week_4/day_2_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Problem 1\n", 8 | "You will work with weather.csv which you can find in the `data` folder. Open the file manually to check its content. The file was scraped from a weather forecast site and the foue columns describe the period for which the forecast is made, a short weather description, temperature, and a long description. Please read the content of the file into a pandas data frame. \n" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "# Problem 2\n", 23 | "\n", 24 | "Add a new column to weather.csv which contains the temperature in Celsius." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "# Problem 3\n", 39 | "\n", 40 | "We have the following datasets from three major social media platforms:\n", 41 | "\n", 42 | "```['Joseph','Jacob','Adella','Ziana','Mickey']```; ```[15, 23, 95, 135, 212]``` (Name, total time spent yesterday on Facebook)\n", 43 | "\n", 44 | "```['Shirly','Jacob','Ximena','Rachel','Mickey']```; ```[9, 31, 78, 115, 198]``` (Name, total time spent yesterday on Twitter)\n", 45 | "\n", 46 | "```['Angie','Mickey','Rachel','Jacob','Andras']```; ```[82, 13, 5, 2, 124]``` (Name, total time spent yesterday on Youtube)\n", 47 | "\n", 48 | "Please convert them into three pandas dataframes.\n", 49 | "\n", 50 | "Answer the following questions. " 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "How many users are on all three platforms?" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [] 73 | }, 74 | { 75 | "cell_type": "markdown", 76 | "metadata": {}, 77 | "source": [ 78 | "Create a dataframe that counts the total number of minutes spent across all platforms by each user. (1 point)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "Twitter would like to know how many minutes its users spend on other social media platforms. (2 points)" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [] 101 | } 102 | ], 103 | "metadata": { 104 | "kernelspec": { 105 | "display_name": "Python 3", 106 | "language": "python", 107 | "name": "python3" 108 | }, 109 | "language_info": { 110 | "codemirror_mode": { 111 | "name": "ipython", 112 | "version": 3 113 | }, 114 | "file_extension": ".py", 115 | "mimetype": "text/x-python", 116 | "name": "python", 117 | "nbconvert_exporter": "python", 118 | "pygments_lexer": "ipython3", 119 | "version": "3.8.8" 120 | } 121 | }, 122 | "nbformat": 4, 123 | "nbformat_minor": 4 124 | } 125 | -------------------------------------------------------------------------------- /week_4/day_2_pandas.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "#
Pandas, part 2
\n", 12 | "### By the end of this talk, you will be able to\n", 13 | " - modify/clean columns\n", 14 | " - evaluate the runtime of your scripts\n", 15 | " - merge and append data frames" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "slide" 23 | } 24 | }, 25 | "source": [ 26 | "### By the end of this talk, you will be able to\n", 27 | " - **modify/clean columns**\n", 28 | " - **evaluate the runtime of your scripts**\n", 29 | " - merge and append data frames" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": { 35 | "slideshow": { 36 | "slide_type": "slide" 37 | } 38 | }, 39 | "source": [ 40 | "## What is data cleaning?\n", 41 | "- the data you scrape from sites are often not in a format you can directly work with\n", 42 | " - the temp column in weather.csv contains the temperature value but also other strings\n", 43 | " - the year column in imdb.csv contains the year the movie came out but also - or () and roman numbers\n", 44 | "- data cleaning means that you bring the data in a format that's easier to analyze/visualize " 45 | ] 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "metadata": { 50 | "slideshow": { 51 | "slide_type": "slide" 52 | } 53 | }, 54 | "source": [ 55 | "## How is it done?\n", 56 | "- you read in your data into a pandas data frame and either \n", 57 | " - modify the values of a column\n", 58 | " - create a new column that contains the modified values\n", 59 | "- either works, I'll show you how to do both\n", 60 | "- ADVICE: when you save the modified data frame, it is usually good practice to not overwrite the original csv or excel file that you scraped. \n", 61 | " - save the modified data into a new file instead" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "## Ways to modify a column\n", 69 | "- there are several ways to do this\n", 70 | " - with a for loop\n", 71 | " - with a list comprehension\n", 72 | " - using the .apply method\n", 73 | "- we will compare run times\n", 74 | " - investigate which approach is faster\n", 75 | " - important when you work with large datasets (>1,000,000 lines)" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": { 81 | "slideshow": { 82 | "slide_type": "slide" 83 | } 84 | }, 85 | "source": [ 86 | "## The task: runtime column in imdb.csv\n", 87 | "- the column is string in the format 'n min' where n is the length of the movie in minutes\n", 88 | "- for plotting purposes, it is better if the runtime is not a string but a number (float or int)\n", 89 | " - you can't create a histogram of runtime using strings\n", 90 | "- task: clean the runtime column and convert it to float" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": { 96 | "slideshow": { 97 | "slide_type": "slide" 98 | } 99 | }, 100 | "source": [ 101 | "## Approach 1: for loop" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 1, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "name": "stdout", 111 | "output_type": "stream", 112 | "text": [ 113 | " title year \\\n", 114 | "0 Get Paid, Get Laid & Get Lucky (2019) \n", 115 | "1 Izzy Got the Frizzies (2019) \n", 116 | "2 Blakus (2019) \n", 117 | "3 DNA (I) (2019) \n", 118 | "4 Matar a un Muerto (2019) \n", 119 | "\n", 120 | " genre runtime rating \\\n", 121 | "0 \\nCrime, Drama, Romance 86 min 7.0 \n", 122 | "1 \\nAnimation, Action, Adventure NaN 4.8 \n", 123 | "2 \\nComedy, Drama, Romance 80 min 7.1 \n", 124 | "3 \\nDrama 126 min 7.8 \n", 125 | "4 \\nThriller 87 min 7.6 \n", 126 | "\n", 127 | " synopsis director vote \n", 128 | "0 \\n A young man,driven only by his dreams,wi... Goran Pavisic 65 \n", 129 | "1 \\n Whether you have naturally frizzy hair o... Ki-duk Kim 11 \n", 130 | "2 \\n Louise and Kaspars meet on a trip to cel... Alise Zarina 312 \n", 131 | "3 \\n A woman with a genetic disease, decides ... Ashay Javadekar 8 \n", 132 | "4 \\n In 1978, Paraguay lives a dictatorship a... Hugo Giménez 8 \n" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "# read in the data\n", 138 | "import pandas as pd\n", 139 | "df_imdb = pd.read_csv('data/imdb.csv')\n", 140 | "print(df_imdb.head())" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 2, 146 | "metadata": {}, 147 | "outputs": [ 148 | { 149 | "name": "stdout", 150 | "output_type": "stream", 151 | "text": [ 152 | "cpu time = 0.41921210289001465 sec\n" 153 | ] 154 | } 155 | ], 156 | "source": [ 157 | "import time\n", 158 | "\n", 159 | "start = time.time() # start the clock\n", 160 | "\n", 161 | "for i in range(100): # repeat everything 100 times to get better estimate of elapsed time\n", 162 | " # the actual code to clean the runtime column comes here\n", 163 | " runtime_lst = []\n", 164 | " for x in df_imdb['runtime']:\n", 165 | " if type(x) == str:\n", 166 | " runtime = float(x[:-4].replace(',',''))\n", 167 | " else:\n", 168 | " runtime = 0e0\n", 169 | " runtime_lst.append(runtime)\n", 170 | " df_imdb['runtime min'] = runtime_lst\n", 171 | " \n", 172 | "end = time.time() # stop the timer\n", 173 | "\n", 174 | "print('cpu time = ',end-start,'sec')" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "metadata": {}, 180 | "source": [ 181 | "## Approach 2: list comprehension" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": 3, 187 | "metadata": {}, 188 | "outputs": [ 189 | { 190 | "name": "stdout", 191 | "output_type": "stream", 192 | "text": [ 193 | "cpu time = 0.31636476516723633 sec\n" 194 | ] 195 | } 196 | ], 197 | "source": [ 198 | "start = time.time() # start the clock\n", 199 | "\n", 200 | "for i in range(100): # repeat everything 100 times to get better estimate of elapsed time\n", 201 | " # the actual code to clean the runtime column comes here\n", 202 | " df_imdb['runtime min'] = [float(x[:-4].replace(',','')) if type(x) == str else 0e0 for x in df_imdb['runtime']]\n", 203 | "end = time.time() # stop the timer\n", 204 | "\n", 205 | "print('cpu time = ',end-start,'sec')" 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "metadata": {}, 211 | "source": [ 212 | "## Approach 3: the .apply method" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 4, 218 | "metadata": {}, 219 | "outputs": [ 220 | { 221 | "name": "stdout", 222 | "output_type": "stream", 223 | "text": [ 224 | "cpu time = 0.30475878715515137 sec\n" 225 | ] 226 | } 227 | ], 228 | "source": [ 229 | "def clean_runtime(x):\n", 230 | " if type(x) == str:\n", 231 | " runtime = float(x[:-4].replace(',',''))\n", 232 | " else:\n", 233 | " runtime = 0e0\n", 234 | " return runtime\n", 235 | "\n", 236 | "start = time.time() # start the clock\n", 237 | "\n", 238 | "for i in range(100): # repeat everything 100 times to get better estimate of elapsed time\n", 239 | " # the actual code to clean the runtime column comes here\n", 240 | " df_imdb['runtime min'] = df_imdb['runtime'].apply(clean_runtime)\n", 241 | "end = time.time() # stop the timer\n", 242 | "\n", 243 | "print('cpu time = ',end-start,'sec')" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "## Summary\n", 251 | "- the for loop is slower\n", 252 | "- the list comprehension and the apply method are equally quick\n", 253 | "- it is down to personal preference to choose between list comprehension and .apply\n", 254 | "- **the same ranking is not quaranteed for a different task!**\n", 255 | " - **always try a few different approaches if runtime is an issue (you work with large data)!**" 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": { 261 | "slideshow": { 262 | "slide_type": "slide" 263 | } 264 | }, 265 | "source": [ 266 | "## Exercise 1\n", 267 | "Clean the `temp` column in the `data/weather.csv` file. The new temperature column should be an integer or a float. Work through at least one of the approaches we discussed. If you have time, work through all three methods. If you have even more time, look for other approaches to clean a column and time it using the `runtime` column of the imdb.csv. Try to beat my cpu time and find an even faster approach! :)" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": { 280 | "slideshow": { 281 | "slide_type": "slide" 282 | } 283 | }, 284 | "source": [ 285 | "### By the end of this talk, you will be able to\n", 286 | " - modify/clean columns\n", 287 | " - evaluate the runtime of your scripts\n", 288 | " - **merge and append data frames**" 289 | ] 290 | }, 291 | { 292 | "cell_type": "markdown", 293 | "metadata": { 294 | "slideshow": { 295 | "slide_type": "subslide" 296 | } 297 | }, 298 | "source": [ 299 | "### How to merge dataframes?\n", 300 | "\n", 301 | "Merge - data are distributed in multiple files" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 5, 307 | "metadata": { 308 | "slideshow": { 309 | "slide_type": "-" 310 | } 311 | }, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | " ID col1 col2\n", 318 | "0 ID1 5 y\n", 319 | "1 ID2 8 j\n", 320 | "2 ID3 2 w\n", 321 | "3 ID4 6 b\n", 322 | "4 ID5 0 a\n", 323 | "5 ID6 2 b\n", 324 | "6 ID7 5 t\n", 325 | " ID col3 col2\n", 326 | "0 ID2 12 q\n", 327 | "1 ID5 76 u\n", 328 | "2 ID6 34 e\n", 329 | "3 ID10 98 l\n", 330 | "4 ID11 65 p\n" 331 | ] 332 | } 333 | ], 334 | "source": [ 335 | "# We have two datasets from two hospitals\n", 336 | "\n", 337 | "hospital1 = {'ID':['ID1','ID2','ID3','ID4','ID5','ID6','ID7'],'col1':[5,8,2,6,0,2,5],'col2':['y','j','w','b','a','b','t']}\n", 338 | "df1 = pd.DataFrame(data=hospital1)\n", 339 | "print(df1)\n", 340 | "\n", 341 | "hospital2 = {'ID':['ID2','ID5','ID6','ID10','ID11'],'col3':[12,76,34,98,65],'col2':['q','u','e','l','p']}\n", 342 | "df2 = pd.DataFrame(data=hospital2)\n", 343 | "print(df2)\n", 344 | "\n" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 6, 350 | "metadata": { 351 | "slideshow": { 352 | "slide_type": "slide" 353 | } 354 | }, 355 | "outputs": [], 356 | "source": [ 357 | "# we are interested in only patients from hospital1\n", 358 | "#df_left = df1.merge(df2,how='left',on='ID') # IDs from the left dataframe (df1) are kept\n", 359 | "#print(df_left)\n", 360 | "\n", 361 | "# we are interested in only patients from hospital2\n", 362 | "#df_right = df1.merge(df2,how='right',on='ID') # IDs from the right dataframe (df2) are kept\n", 363 | "#print(df_right)\n", 364 | "\n", 365 | "# we are interested in patiens who were in both hospitals\n", 366 | "#df_inner = df1.merge(df2,how='inner',on='ID') # merging on IDs present in both dataframes\n", 367 | "#print(df_inner)\n", 368 | "\n", 369 | "# we are interested in all patients who visited at least one of the hospitals\n", 370 | "#df_outer = df1.merge(df2,how='outer',on='ID') # merging on IDs present in any dataframe\n", 371 | "#print(df_outer)" 372 | ] 373 | }, 374 | { 375 | "cell_type": "markdown", 376 | "metadata": { 377 | "slideshow": { 378 | "slide_type": "subslide" 379 | } 380 | }, 381 | "source": [ 382 | "### How to append dataframes?\n", 383 | "\n", 384 | "Append - new data comes in over a period of time. E.g., one file per month/quarter/fiscal year etc.\n", 385 | "\n", 386 | "\n", 387 | "You want to combine these files into one data frame." 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": 7, 393 | "metadata": {}, 394 | "outputs": [ 395 | { 396 | "name": "stdout", 397 | "output_type": "stream", 398 | "text": [ 399 | " ID col1 col2 col3\n", 400 | "0 ID1 5 y NaN\n", 401 | "1 ID2 8 j NaN\n", 402 | "2 ID3 2 w NaN\n", 403 | "3 ID4 6 b NaN\n", 404 | "4 ID5 0 a NaN\n", 405 | "5 ID6 2 b NaN\n", 406 | "6 ID7 5 t NaN\n", 407 | "7 ID2 NaN q 12.0\n", 408 | "8 ID5 NaN u 76.0\n", 409 | "9 ID6 NaN e 34.0\n", 410 | "10 ID10 NaN l 98.0\n", 411 | "11 ID11 NaN p 65.0\n", 412 | "12 ID23 rt 23 NaN\n", 413 | "13 ID94 h 86 NaN\n", 414 | "14 ID56 st 23 NaN\n", 415 | "15 ID17 ne 78 NaN\n" 416 | ] 417 | } 418 | ], 419 | "source": [ 420 | "#df_append = df1.append(df2) # note that rows with ID2, ID5, and ID6 are duplicated! Indices are duplicated too.\n", 421 | "#print(df_append)\n", 422 | "\n", 423 | "df_append = df1.append(df2,ignore_index=True) # note that rows with ID2, ID5, and ID6 are duplicated! \n", 424 | "#print(df_append)\n", 425 | "\n", 426 | "d3 = {'ID':['ID23','ID94','ID56','ID17'],'col1':['rt','h','st','ne'],'col2':[23,86,23,78]}\n", 427 | "df3 = pd.DataFrame(data=d3)\n", 428 | "#print(df3)\n", 429 | "\n", 430 | "df_append = df1.append([df2,df3],ignore_index=True) # multiple dataframes can be appended to df1\n", 431 | "print(df_append)\n", 432 | "\n" 433 | ] 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "metadata": { 438 | "slideshow": { 439 | "slide_type": "skip" 440 | } 441 | }, 442 | "source": [ 443 | "### Exercise 2\n", 444 | "- Create three data frames from raw_data_1, 2, and 3.\n", 445 | "- Append the first two data frames and assign it to df_append.\n", 446 | "- Merge the third data frame with df_append such that only subject_ids from df_append are present. \n", 447 | "- Assign the new data frame to df_merge. \n", 448 | "- How many rows and columns do we have in df_merge?\n" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": 8, 454 | "metadata": { 455 | "slideshow": { 456 | "slide_type": "skip" 457 | } 458 | }, 459 | "outputs": [], 460 | "source": [ 461 | "\n", 462 | "raw_data_1 = {\n", 463 | " 'subject_id': ['1', '2', '3', '4', '5'],\n", 464 | " 'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], \n", 465 | " 'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}\n", 466 | "\n", 467 | "raw_data_2 = {\n", 468 | " 'subject_id': ['6', '7', '8', '9', '10'],\n", 469 | " 'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], \n", 470 | " 'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']}\n", 471 | "\n", 472 | "raw_data_3 = {\n", 473 | " 'subject_id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'],\n", 474 | " 'test_id': [51, 15, 15, 61, 16, 14, 15, 1, 61, 16]}\n" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": { 481 | "slideshow": { 482 | "slide_type": "skip" 483 | } 484 | }, 485 | "outputs": [], 486 | "source": [] 487 | }, 488 | { 489 | "cell_type": "markdown", 490 | "metadata": { 491 | "slideshow": { 492 | "slide_type": "slide" 493 | } 494 | }, 495 | "source": [ 496 | "### Always check that the resulting dataframe is what you wanted to end up with!\n", 497 | "- small toy datasets are ideal to test your code.\n", 498 | "\n", 499 | "### If you need to do a more complicated dataframe operation, check out pd.concat()!\n" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [] 508 | } 509 | ], 510 | "metadata": { 511 | "celltoolbar": "Slideshow", 512 | "kernelspec": { 513 | "display_name": "Python 3", 514 | "language": "python", 515 | "name": "python3" 516 | }, 517 | "language_info": { 518 | "codemirror_mode": { 519 | "name": "ipython", 520 | "version": 3 521 | }, 522 | "file_extension": ".py", 523 | "mimetype": "text/x-python", 524 | "name": "python", 525 | "nbconvert_exporter": "python", 526 | "pygments_lexer": "ipython3", 527 | "version": "3.8.8" 528 | } 529 | }, 530 | "nbformat": 4, 531 | "nbformat_minor": 4 532 | } 533 | -------------------------------------------------------------------------------- /week_4/day_3_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Prepare a visualization using these columns in the adult data. Alternatively, feel free to use any other dataset you'd like to work with. Don't forget to add axis labels, titles, make the figure publication ready." 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "age" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "gross income vs hours-per-week" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "marital status" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [] 51 | } 52 | ], 53 | "metadata": { 54 | "kernelspec": { 55 | "display_name": "Python 3", 56 | "language": "python", 57 | "name": "python3" 58 | }, 59 | "language_info": { 60 | "codemirror_mode": { 61 | "name": "ipython", 62 | "version": 3 63 | }, 64 | "file_extension": ".py", 65 | "mimetype": "text/x-python", 66 | "name": "python", 67 | "nbconvert_exporter": "python", 68 | "pygments_lexer": "ipython3", 69 | "version": "3.8.8" 70 | } 71 | }, 72 | "nbformat": 4, 73 | "nbformat_minor": 4 74 | } 75 | -------------------------------------------------------------------------------- /week_4/day_4_lab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Problem 1\n", 8 | "\n", 9 | "Prepare one figure per column vs. gross income! Make publication-ready figures. Which columns show the strongest correlation with respect to the gross income? Which columns do not appear to be correlated with gross income?" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [] 18 | } 19 | ], 20 | "metadata": { 21 | "kernelspec": { 22 | "display_name": "Python 3", 23 | "language": "python", 24 | "name": "python3" 25 | }, 26 | "language_info": { 27 | "codemirror_mode": { 28 | "name": "ipython", 29 | "version": 3 30 | }, 31 | "file_extension": ".py", 32 | "mimetype": "text/x-python", 33 | "name": "python", 34 | "nbconvert_exporter": "python", 35 | "pygments_lexer": "ipython3", 36 | "version": "3.8.8" 37 | } 38 | }, 39 | "nbformat": 4, 40 | "nbformat_minor": 4 41 | } 42 | -------------------------------------------------------------------------------- /workshop.yml: -------------------------------------------------------------------------------- 1 | name: workshop 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - python=3.8.8 7 | - matplotlib=3.3.2 8 | - pandas=1.2.4 9 | - jupyter_client 10 | - jupyter_core 11 | - jupyterlab 12 | - jupyterlab_server 13 | - ipywidgets 14 | - jupytext 15 | - rise 16 | prefix: /opt/conda 17 | 18 | --------------------------------------------------------------------------------