{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![](../docs/banner.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Style Guides, Scripts, Imports\n", "\n", "**Tomas Beuzen, September 2020**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These exercises complement [Chapter 4](../chapters/chapter4-style-scripts-imports.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `flake8` to list all the syntatic and stylistic problems with the following code. You could copy the code into a `.py` file and run `flake8` from the command line (as was shown in [Chapter 4](../chapters/chapter4-style-scripts-imports.ipynb)), or you could try the [JupyterLab flake8 extension](https://github.com/mlshapiro/jupyterlab-flake8)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "very_long_variable_name = {'field': 1,\n", " 'is_debug': True}\n", "if very_long_variable_name is not None and very_long_variable_name[\"field\"] > 0 or very_long_variable_name['is_debug']:\n", " z = 'hello '+'world'\n", "else:\n", " f = rf'hello {world}'\n", "if (True): y = 'hello ''world'#FIXME: https://github.com/python/black/issues/26\n", "class Foo ( object ):\n", " def f (self ):\n", " return 37*-2\n", " def g(self, x,y=42):\n", " return y\n", "regular_formatting = [\n", " 0, 1, 2,\n", " 3, 4, 5\n", "]\n", "def CAPITALIZE(mystring):\n", " return mystring.upper()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Your answer here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `black` to autoformat the following code. You could copy the code into a `.py` file and run `black` from the command line (as was shown in [Chapter 4](../chapters/chapter4-style-scripts-imports.ipynb)), or you could try the [JupyterLab black extension](https://jupyterlab-code-formatter.readthedocs.io/en/latest/index.html)." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "very_long_variable_name = {'field': 1,\n", " 'is_debug': True}\n", "if very_long_variable_name is not None and very_long_variable_name[\"field\"] > 0 or very_long_variable_name['is_debug']:\n", " z = 'hello '+'world'\n", "else:\n", " f = rf'hello {world}'\n", "if (True): y = 'hello ''world'#FIXME: https://github.com/python/black/issues/26\n", "class Foo ( object ):\n", " def f (self ):\n", " return 37*-2\n", " def g(self, x,y=42):\n", " return y\n", "regular_formatting = [\n", " 0, 1, 2,\n", " 3, 4, 5\n", "]\n", "def CAPITALIZE(mystring):\n", " return mystring.upper()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Your answer here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the [last set of practice exercises](chapter3-tests-classes-practice.ipynb) we created the `Circle` class:\n", "\n", "```python\n", "class Circle:\n", " \"\"\"A circle with a radius r.\"\"\"\n", "\n", " def __init__(self, radius):\n", " self.radius = radius\n", "\n", " def area(self):\n", " \"\"\"Calculate the area of the circle.\"\"\"\n", " return math.pi * self.radius ** 2\n", "\n", " def circumference(self):\n", " \"\"\"Calculate the circumference of the circle.\"\"\"\n", " return 2.0 * math.pi * self.radius\n", "\n", " def __str__(self):\n", " return f\"A Circle with radius {self.radius}\"\n", "```\n", "\n", "Save this code into a new Python `.py` file and then import it here and answer the following:\n", "\n", "1. What is the area of a circle with radius 10?\n", "2. What is the circumference of a circle with radius 10?" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Your answer here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I recently decided to simulate the possible attendance at a party I was throwing using Python. The idea is that for every guest you invite, you assign them a probability of actually attending your party. For example:\n", "\n", "\n", "| Guest Name | Probability of Attending |\n", "|------------|--------------------------|\n", "| Tom | 1 |\n", "| Varada | 0.75 |\n", "| Tiffany | 0.5 |\n", "| Joel | 0.75 |\n", "| Alexi | 0.5 |\n", "| Joel | 1 |\n", "| Mike | 0.5 |\n", "| Hayley | 0.75 |\n", "\n", "In this exercise I want you to create a function that models each guest's attendance as a [Bernoulli random variable](https://en.wikipedia.org/wiki/Bernoulli_distribution). You can run a Bernoulli trial using the `numpy` library function `random.binomial(n=1, ...)` (here are the [docs](https://numpy.org/doc/stable/reference/random/generated/numpy.random.binomial.html)). You should import this function and run a single simulation on the list above (note that results may vary as we won't fix the random seed here).\n", "\n", "I've given you the list of probabilities to get you started. Your code should output the total number of attendees after running your simulation.\n", "\n", "*This question is based on a [random website post I made recently](https://www.tomasbeuzen.com/post/party-planning-probability/).*" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "probabilities = [1, 0.75, 0.5, 0.75, 0.5, 1, 0.5, 0.75]\n", "\n", "# Your answer here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So after completing Exercise 4, you have a way of running a single simulation given a list of probabilities. Now I want you to write a function called `simulate_party(probabilities, n)` that runs `n` simulations for a list of `probabilities` and returns a list of the total number of attendees for each simulation.\n", "\n", "Then, calculate the average guest attendance after running 100 simulations (round up to the nearest integer - hint: `math.ceil()`)." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def simulate_party(probabilities, n):\n", " \"Simulate attendance at a party from a list of attendance probabilities.\"\n", " pass # Remove this line and add your answer here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you have a working function, uncomment the code below to plot the results of your function on a much longer guest list!" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "tags": [ "raises-exception" ] }, "outputs": [], "source": [ "# Use this code to plot your function on a bigger guest list!\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "plt.style.use('ggplot') # These lines are to do with plot formatting. We'll talk about them in a later chapter.\n", "plt.rcParams.update({'font.size': 16, 'axes.labelweight': 'bold', 'figure.figsize': (8, 6)})\n", "\n", "number_of_guests=100\n", "probabilities = np.random.choice([0.2, 0.4, 0.6, 0.8, 1],\n", " size=number_of_guests,\n", " p=[0.1, 0.2, 0.2, 0.3, 0.2])\n", "\n", "# attendance = simulate_party(probabilities, n=1000)\n", "# plt.hist(attendance, bins=20)\n", "# plt.xlabel(\"Avg. number of attendees\")\n", "# plt.ylabel(\"Number of simulations\");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "