From 05fecfa1ff0184c0372fc807d6778d556f9e560a Mon Sep 17 00:00:00 2001 From: Luigi Petrucco Date: Thu, 14 Mar 2024 00:32:44 +0100 Subject: [PATCH] Assignment 0.0 --- README.md | 3 +- assignments/Assignments_0.ipynb | 351 ++++++++++++++++++++++++++++ lectures/Lecture0.3_Functions.ipynb | 276 +++++++++++++++------- practicals/Practicals_0.1.ipynb | 42 ++-- practicals/Practicals_0.2.ipynb | 2 - practicals/Practicals_0.3.ipynb | 164 +++++++++++-- 6 files changed, 701 insertions(+), 137 deletions(-) create mode 100644 assignments/Assignments_0.ipynb diff --git a/README.md b/README.md index 043ed60..05b6470 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ This course will start covering **the basics of Python usage** and build up from ## Lectures recordings - [Lecture 0.1](https://youtu.be/TMss3OOHrLE): Data structures (list, dict, tuple, set) -- [Lecture 0.2](https://youtu.be/34A9iWaIqvM): Flow controls (if/else, for) +- [Lecture 0.2](https://youtu.be/34A9iWaIqvM): Flow controls (if/else, for loops) +- [Lecture 0.3](https://youtu.be/ZlN6qyjW488): while loops; functions --- diff --git a/assignments/Assignments_0.ipynb b/assignments/Assignments_0.ipynb new file mode 100644 index 0000000..b9ffd83 --- /dev/null +++ b/assignments/Assignments_0.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "f54dd50c", + "metadata": {}, + "source": [ + "# Assignments - module 0\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/vigji/python-cimec/blob/main/assignments/Assignments_0.ipynb)\n", + "\n", + "This notebook contains the assignments to complete for credits for the first module. \n", + "\n", + "**Submission**: Once you're happy with your solutions, send it to me in any form (email the file, share it through Colab/Google Drive, send me a link to your GitHub repo...).\n", + "\n", + "**Deadline**: 15th of July 2024\n", + "\n", + "**Evaluation**: There is no grade, but I will pass assignments that showcase a reasonable degree of understanding og the covered topics. Do your best, and feel free to ask for help if you are struggling! \n", + "\n", + "(Also, try to keep in mind not only the goal of the exercise, but also all the coding best practices we have been considering in the lectures.)" + ] + }, + { + "cell_type": "markdown", + "id": "9ce5d72f", + "metadata": {}, + "source": [ + "# 0. Cryptography\n", + "\n", + "The [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) is a simple encryption technique where each letter in the plaintext is shifted a certain number of places down or up the alphabet. For example, with a shift of 1, 'A' becomes 'B', 'B' becomes 'C', etc., and 'Z' would wrap around to 'A'." + ] + }, + { + "cell_type": "markdown", + "id": "e2cb8832", + "metadata": {}, + "source": [ + "#### Exercise 0.0\n", + "\n", + "The first thing that we will need to work with this cipher is a way to shift a given letter text up or down the alphabet.\n", + "This could be done in two ways:\n", + "1. Start from a list (or a string) of all letters of the alphabet; find the index of the letter to encrypt; add the given shift to the index, and use this new index to find the new letter\n", + "2. Rely on [ASCII](https://en.wikipedia.org/wiki/ASCII) encoding of characters to map each letter to its integer ascii encoding with the `ord()` function, add the shift to the integer, and convert it back with the `chr()` function\n", + "\n", + "Make sure that your code works with any possible positive or negative shift over the English alphabet (hint: remember the modulo operation...)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "148bebac", + "metadata": {}, + "outputs": [], + "source": [ + "letter_to_convert = \"a\" # try different letters\n", + "shift = 4 # play with different values\n", + "\n", + "...\n", + "\n", + "encoded_letter = ..." + ] + }, + { + "cell_type": "markdown", + "id": "0f2c0ea9", + "metadata": {}, + "source": [ + "#### Exercise 0.1\n", + "\n", + "Now, let's use the code above to encode/decode full words! (note that the same code can either decode a encrypted message or decode a plaintext message, using positive and negative shifts)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96be39c2", + "metadata": {}, + "outputs": [], + "source": [ + "# Write a function that takes a word and a shift as input, and returns the shifted text as output\n", + "# (e.g., word=\"hello\", shift=1 should produce \"ifmmp\")\n", + "\n", + "def shift_word(word, shift):\n", + " ...\n" + ] + }, + { + "cell_type": "markdown", + "id": "12c57f2b", + "metadata": {}, + "source": [ + "#### Exercise 0.2\n", + "\n", + "Longer texts will have uppercase words and punctuation. Starting from the function of exercise 0.1, write a new function that can handle more complex text, and return its encrypted version." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "343aa483", + "metadata": {}, + "outputs": [], + "source": [ + "# Write a function that takes a word and a shift as input, and returns the shifted text as output\n", + "# (e.g., text=\"\"Hello, World!\"\", shift=1 should produce \"Ifmmp, Xpsme!\")\n", + "# Hint: you can check out if a character is a letter with the .isalpha() method\n", + "\n", + "def shift_text(text, shift):\n", + " ..." + ] + }, + { + "cell_type": "markdown", + "id": "d3916d37", + "metadata": {}, + "source": [ + "#### [optional] Exercise 0.3\n", + "Sometimes, we do not know in advance the register shift ([they certainly did not know it at Bletchley Part](https://en.wikipedia.org/wiki/Bombe)). Still, we could leverage a brute force attack to test all possible combinations (there are only 26!) and check each solution agains an English dictionary (assuming that the original message will be in English), to see which shift gives the best matching" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "52bf9351", + "metadata": {}, + "outputs": [], + "source": [ + "# Here' a function that will give you a reasonable list of English words:\n", + "import requests\n", + "\n", + "\n", + "def get_english_words_list():\n", + " \"\"\"Download a reasonably complete English dictionary.\"\"\"\n", + " resp = requests.get(\"https://www.mit.edu/~ecprice/wordlist.10000\")\n", + " return resp.text.split(\"\\n\")\n", + "\n", + "english_words = get_english_words_list() # here's how to get a list of english words" + ] + }, + { + "cell_type": "markdown", + "id": "b525f519", + "metadata": {}, + "source": [ + "## 1. Spotted UniTn" + ] + }, + { + "cell_type": "markdown", + "id": "db12042e", + "metadata": {}, + "source": [ + "In this exercise, we'll be doing some stats on a dataset of all the people employed at UniTn scraped from the UniTn website.\n", + "\n", + "**Note**: We have not learned yet how to use arrays, matrices, and dataframes. Some of the analysis in this exercise will inevitabily look a bit cumbersome, because they are - with the tools we have now. They'll become a piece of cake with `pandas`!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56ff6ba0", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import requests\n", + "\n", + "\n", + "def get_unitn_hr_dataset():\n", + " \"\"\"Download all data about UniTn employees from their website.\n", + "\n", + " !!!Note: all information we are using here is made openly available from\n", + " the university. However, please do appreciate the power of similar data\n", + " scraping through any of the online platforms we're giving our data to,\n", + " were there some security holes!\n", + " This is no endorsment toward trying anything like that yourself, hacking\n", + " is bad. No seriously, it is. Also, copyright is good.\n", + "\n", + " Returns:\n", + "\n", + " list : A list of uni employees.\n", + "\n", + " \"\"\"\n", + "\n", + " # This string contains the address at which we'll find the dataset:\n", + " UNITN_PEOPLE_URL = \"https://dati.unitn.it/du/Person/en\"\n", + "\n", + " # Get page response:\n", + " response = requests.get(UNITN_PEOPLE_URL)\n", + "\n", + " # Parse a json from the page:\n", + " json_data = json.loads(response.text)\n", + "\n", + " # Get actual data and return:\n", + " return json_data[\"value\"][\"data\"]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae543d19", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "669c931b", + "metadata": {}, + "source": [ + "#### Exercise 1.0\n", + "\n", + "Call the function and try to have a look at the result. How many people are employed at the university? How many at each department? Which is the deparment with the most professors?\n", + "\n", + "Make a nice `print` of all those results! (You'll see a lot of different departments. You can filter results for the ones with at least 10 people)\n", + "\n", + "- If people have multiple affiliations, count them in each one of them. Eg, if someone is listed under both `\"Center for Mind/Brain Sciences - CIMeC\"` and `\"CeRiN - Center for Neurocognitive Rehabilitation\"`, put the person in the count for both departments.\n", + "- If a person is listed with two different roles at the same department (e.g., as both `\"Graduate student\"` and `\"Research intern\"`) count that person only once for that department." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "60e39898", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "db624bbe", + "metadata": {}, + "source": [ + "#### Exercise 1.1\n", + "\n", + "Imagine you want to call-bomb the `\"Department of Economics and Management\"` for a prank. You'll first need a list of all the phone numbers you can find in that department. Create that list!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f560dd1", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "759cf40d", + "metadata": {}, + "source": [ + "#### Exercise 1.2\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "999a6f38", + "metadata": {}, + "source": [ + "Use the function below to get a dictionary of Italian names divided by gender. \n", + "\n", + "Then, print out the gender ratio (how many women, how many men) for all the position roles that you can find in the dataset (filter out positions with less then 10 people). Then, jump to conclusions!\n", + "\n", + "- If a person has multiple roles count them for each of the roles they have\n", + "- Yes, it can be erroneous to infer gender just from the name; here we assume potential errors will average out in the large numbers.\n", + "- Yes, this will consider only Italian employees. You can print out how many names were left out (and which ones), and if you want try and improve the function by including international names in the list as well!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf71c38b", + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "\n", + "def get_names():\n", + " \"\"\"Download a list of italian names, divided by gender.\n", + "\n", + " Returns:\n", + "\n", + " dict : A dictionary of masculine and feminine names.\n", + "\n", + " \"\"\"\n", + "\n", + " # This string contains the address at which we'll find the names:\n", + " FIRST_NAMES_URL = \"https://gist.githubusercontent.com/metalelf0/a2ab283d0d5fd9b4b8a10d6427630627/raw/b848ffee70464fd39714a1a621f3a2eba6c3812e/italian_names.md\"\n", + "\n", + " # Get page response:\n", + " response = requests.get(FIRST_NAMES_URL)\n", + "\n", + " # read the response as string:\n", + " raw_content = response.text\n", + "\n", + " # split lines and exclude fir header (# Male names):\n", + " full_names_list = raw_content.split(\"\\n\")[1:]\n", + "\n", + " # Look for the header \"# Female names\":\n", + " female_header_idx = full_names_list.index(\"# Female names\")\n", + "\n", + " # Names before header are male, after are female:\n", + " return dict(\n", + " male=full_names_list[:female_header_idx],\n", + " female=full_names_list[female_header_idx + 1 :],\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "d7b0a566", + "metadata": {}, + "source": [ + "## 2. Classes\n", + "\n", + "Pending..." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5209c7cd", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "course-env", + "language": "python", + "name": "course-env" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lectures/Lecture0.3_Functions.ipynb b/lectures/Lecture0.3_Functions.ipynb index ed9a0ac..37dca06 100644 --- a/lectures/Lecture0.3_Functions.ipynb +++ b/lectures/Lecture0.3_Functions.ipynb @@ -20,7 +20,7 @@ }, { "cell_type": "markdown", - "id": "02f32aac", + "id": "a964e0ca", "metadata": { "slideshow": { "slide_type": "subslide" @@ -36,7 +36,7 @@ }, { "cell_type": "markdown", - "id": "bafdd45d", + "id": "d992d181", "metadata": { "slideshow": { "slide_type": "subslide" @@ -48,7 +48,7 @@ }, { "cell_type": "markdown", - "id": "63fb8c22", + "id": "18dcfac2", "metadata": {}, "source": [ "If a variable is `None` no value is assigned to it!" @@ -56,18 +56,18 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "0f22be20", + "execution_count": 18, + "id": "e0e365ba", "metadata": {}, "outputs": [], "source": [ "a = None\n", - "print(a)" + "a" ] }, { "cell_type": "markdown", - "id": "794af21b", + "id": "8cb500a0", "metadata": { "slideshow": { "slide_type": "subslide" @@ -79,8 +79,8 @@ }, { "cell_type": "code", - "execution_count": 22, - "id": "c016a966", + "execution_count": 19, + "id": "a959ba04", "metadata": {}, "outputs": [ { @@ -89,7 +89,7 @@ "False" ] }, - "execution_count": 22, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } @@ -101,8 +101,8 @@ }, { "cell_type": "code", - "execution_count": 23, - "id": "dcfeef9d", + "execution_count": 20, + "id": "ab25f91a", "metadata": {}, "outputs": [ { @@ -111,7 +111,7 @@ "False" ] }, - "execution_count": 23, + "execution_count": 20, "metadata": {}, "output_type": "execute_result" } @@ -122,7 +122,7 @@ }, { "cell_type": "markdown", - "id": "b0da8ad3", + "id": "402ece02", "metadata": { "slideshow": { "slide_type": "subslide" @@ -134,7 +134,7 @@ }, { "cell_type": "markdown", - "id": "79a7ce4c", + "id": "27542f78", "metadata": { "slideshow": { "slide_type": "-" @@ -146,8 +146,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "id": "2ff29b35", + "execution_count": 21, + "id": "37c1fa9f", "metadata": { "slideshow": { "slide_type": "subslide" @@ -160,8 +160,8 @@ }, { "cell_type": "code", - "execution_count": 7, - "id": "9320ffa4", + "execution_count": 22, + "id": "4748879e", "metadata": {}, "outputs": [ { @@ -170,7 +170,7 @@ "True" ] }, - "execution_count": 7, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } @@ -181,8 +181,8 @@ }, { "cell_type": "code", - "execution_count": 8, - "id": "b02611dc", + "execution_count": 23, + "id": "b1d0955a", "metadata": {}, "outputs": [ { @@ -191,7 +191,7 @@ "False" ] }, - "execution_count": 8, + "execution_count": 23, "metadata": {}, "output_type": "execute_result" } @@ -202,8 +202,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "id": "695e8344", + "execution_count": 24, + "id": "711fcc9b", "metadata": {}, "outputs": [ { @@ -212,7 +212,7 @@ "True" ] }, - "execution_count": 9, + "execution_count": 24, "metadata": {}, "output_type": "execute_result" } @@ -243,7 +243,7 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 25, "id": "b759daf8", "metadata": { "slideshow": { @@ -272,14 +272,15 @@ "# Very simple example (this would normally be a \"for\" loop):\n", "\n", "i = 0\n", + "\n", "while i < 10:\n", " print(\"Value of i: \", i)\n", - " i += 1" + " i = i + 1" ] }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 27, "id": "65109c7d", "metadata": { "slideshow": { @@ -291,6 +292,8 @@ "name": "stdout", "output_type": "stream", "text": [ + "Flip: 0\n", + "Flip: 0\n", "Flip: 0\n", "Flip: 1\n" ] @@ -303,13 +306,13 @@ "coin_flip = 0\n", "\n", "while coin_flip == 0:\n", - " coin_flip = random.randint(0, 1)\n", + " coin_flips = random.randint(0, 1)\n", " print(\"Flip: \", coin_flip)" ] }, { "cell_type": "markdown", - "id": "ef8e473c", + "id": "e17ea982", "metadata": {}, "source": [ "Sometimes we can use alternatively `for` or `while`, but in general:\n", @@ -339,10 +342,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "id": "1ae5a83f", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n" + ] + } + ], "source": [ "i = 0\n", "\n", @@ -437,7 +455,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 29, "id": "0216d514", "metadata": {}, "outputs": [ @@ -448,7 +466,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[19], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m a_dict \u001b[38;5;241m=\u001b[39m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124ma\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;241m1\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mb\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;241m2\u001b[39m}\n\u001b[0;32m----> 2\u001b[0m \u001b[43ma_dict\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mc\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\n", + "Cell \u001b[0;32mIn[29], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m a_dict \u001b[38;5;241m=\u001b[39m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124ma\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;241m1\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mb\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;241m2\u001b[39m}\n\u001b[0;32m----> 2\u001b[0m \u001b[43ma_dict\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mc\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\n", "\u001b[0;31mKeyError\u001b[0m: 'c'" ] } @@ -472,7 +490,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 32, "id": "9592f479", "metadata": {}, "outputs": [ @@ -483,7 +501,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[21], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mrandom\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m \u001b[43mrandom\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrandint\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43ma\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n", + "Cell \u001b[0;32mIn[32], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mrandom\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m \u001b[43mrandom\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrandint\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43ma\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/miniconda3/lib/python3.11/random.py:362\u001b[0m, in \u001b[0;36mRandom.randint\u001b[0;34m(self, a, b)\u001b[0m\n\u001b[1;32m 358\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrandint\u001b[39m(\u001b[38;5;28mself\u001b[39m, a, b):\n\u001b[1;32m 359\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"Return random integer in range [a, b], including both end points.\u001b[39;00m\n\u001b[1;32m 360\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[0;32m--> 362\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrandrange(a, \u001b[43mb\u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m)\n", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] @@ -511,7 +529,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 34, "id": "6e0ba7b3", "metadata": { "slideshow": { @@ -526,7 +544,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[10], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mnon_existent_variable\u001b[49m)\n", + "Cell \u001b[0;32mIn[34], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Simple: the variable just does not exist:\u001b[39;00m\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mnon_existent_variable\u001b[49m)\n", "\u001b[0;31mNameError\u001b[0m: name 'non_existent_variable' is not defined" ] } @@ -538,7 +556,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 35, "id": "4f405f0c", "metadata": { "slideshow": { @@ -553,7 +571,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[11], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Subtle: we just have a typo:\u001b[39;00m\n\u001b[1;32m 2\u001b[0m supposedy_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 3\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", + "Cell \u001b[0;32mIn[35], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Subtle: we just have a typo\u001b[39;00m\n\u001b[1;32m 2\u001b[0m supposedy_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 3\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", "\u001b[0;31mNameError\u001b[0m: name 'supposedly_existent_variable' is not defined" ] } @@ -566,7 +584,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 36, "id": "239db948", "metadata": { "slideshow": { @@ -581,7 +599,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[13], line 5\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m a \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 4\u001b[0m supposedly_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 5\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", + "Cell \u001b[0;32mIn[36], line 5\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m a \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m 4\u001b[0m supposedly_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 5\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", "\u001b[0;31mNameError\u001b[0m: name 'supposedly_existent_variable' is not defined" ] } @@ -620,7 +638,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 37, "id": "3a9b1e7c", "metadata": { "slideshow": { @@ -635,7 +653,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[1], line 6\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mI\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mm assuming this line is executed\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 5\u001b[0m supposedly_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", + "Cell \u001b[0;32mIn[37], line 6\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mI\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mm assuming this line is executed\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 5\u001b[0m supposedly_existent_variable \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m----> 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43msupposedly_existent_variable\u001b[49m)\n", "\u001b[0;31mNameError\u001b[0m: name 'supposedly_existent_variable' is not defined" ] } @@ -763,7 +781,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "id": "ca2f9276", "metadata": { "slideshow": { @@ -782,14 +800,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "id": "642f4dd5", "metadata": { "slideshow": { "slide_type": "subslide" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2.5\n" + ] + } + ], "source": [ "def list_average(input_list):\n", " \"\"\"Compute the average of values in a list\"\"\"\n", @@ -863,17 +889,17 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 42, "id": "270f40e1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "8" + "9" ] }, - "execution_count": 1, + "execution_count": 42, "metadata": {}, "output_type": "execute_result" } @@ -887,7 +913,7 @@ "\n", "c = 2\n", "d = 3\n", - "exponentiate(c, d)" + "exponentiate(d, c)" ] }, { @@ -904,10 +930,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, "id": "1b2aafcc", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a=1, b=2, c=5\n" + ] + } + ], "source": [ "# A function with default values:\n", "\n", @@ -916,7 +950,7 @@ " print(f\"a={a}, b={b}, c={c}\")\n", "\n", "\n", - "print_args(1, 2)" + "print_args(1, 2, 5)" ] }, { @@ -937,7 +971,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 47, "id": "7e6a341a", "metadata": { "slideshow": { @@ -949,7 +983,9 @@ "name": "stdout", "output_type": "stream", "text": [ + "By position, variable identity is inferred based on the arguments order\n", "a=1, b=2, c=3\n", + "By keyword, we can specify separately each variable\n", "a=2, b=3, c=1\n" ] } @@ -963,7 +999,7 @@ "print(\"By position, variable identity is inferred based on the arguments order\")\n", "print_args(1, 2, 3)\n", "\n", - "prnt(\"By keyword, we can specify separately each variable\")\n", + "print(\"By keyword, we can specify separately each variable\")\n", "# try passing stuff by keyword:\n", "print_args(c=1, a=2, b=3)" ] @@ -994,7 +1030,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 49, "id": "fee83430", "metadata": { "slideshow": { @@ -1007,8 +1043,19 @@ "output_type": "stream", "text": [ "Input: 2 (); result: 4\n", - "Input: 2.0 (); result: 4.0\n", - "Input: 2 (); result: 22\n" + "Input: 2.0 (); result: 4.0\n" + ] + }, + { + "ename": "TypeError", + "evalue": "unsupported operand type(s) for ** or pow(): 'str' and 'int'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[0;32mIn[49], line 9\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[38;5;66;03m# Test different inputs to the function:\u001b[39;00m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m input_to_test \u001b[38;5;129;01min\u001b[39;00m [\u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m2.\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m2\u001b[39m\u001b[38;5;124m\"\u001b[39m]:\n\u001b[0;32m----> 9\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInput: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00minput_to_test\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m (\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mtype\u001b[39m(input_to_test)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m); result: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[43mmultiply_numbers\u001b[49m\u001b[43m(\u001b[49m\u001b[43minput_to_test\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n", + "Cell \u001b[0;32mIn[49], line 4\u001b[0m, in \u001b[0;36mmultiply_numbers\u001b[0;34m(input_number)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mmultiply_numbers\u001b[39m(input_number):\n\u001b[0;32m----> 4\u001b[0m \u001b[43minput_number\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\n\u001b[1;32m 5\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m input_number \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m2\u001b[39m\n", + "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for ** or pow(): 'str' and 'int'" ] } ], @@ -1016,6 +1063,7 @@ "# This will run the function and produce unexpected\n", "# results with the wrong input type, without giving errors:\n", "def multiply_numbers(input_number):\n", + " input_number ** 2\n", " return input_number * 2\n", "\n", "# Test different inputs to the function:\n", @@ -1166,7 +1214,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 50, "id": "b0b750ae", "metadata": { "slideshow": { @@ -1187,23 +1235,69 @@ "# Those two functions return the same value:\n", "def print_function_0():\n", " print(\"Function 0 called\")\n", - " return None\n", + " return \n", "\n", "def print_function_1():\n", " print(\"Function 1 called\")\n", "\n", - "\n", "print(print_function_0())" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 57, + "id": "481dfbd2", + "metadata": { + "slideshow": { + "slide_type": "subslide" + } + }, + "outputs": [], + "source": [ + "\n", + "def return_fixed_values():\n", + " return 1, \"a\"" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "id": "7603dd46", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a\n" + ] + } + ], + "source": [ + "value0, value1 = (\"a\", 2)\n", + "print(value0)" + ] + }, + { + "cell_type": "code", + "execution_count": 65, "id": "c7afc366", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 'a')" + ] + }, + "execution_count": 65, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "print(print_function_1())" + "value0 = return_fixed_values()\n", + "value0" ] }, { @@ -1307,7 +1401,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 66, "id": "14717eb1", "metadata": { "slideshow": { @@ -1335,25 +1429,17 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 67, "id": "e648b1c4", "metadata": { "slideshow": { "slide_type": "subslide" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Object `exponentiate` not found.\n" - ] - } - ], + "outputs": [], "source": [ "# We can read out documentation for our custom functions:\n", - "?exponentiate" + " exponentiate" ] }, { @@ -1386,14 +1472,26 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 68, "id": "dd4fed8a", "metadata": { "slideshow": { "slide_type": "subslide" } }, - "outputs": [], + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'local_sum_variable' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[0;32mIn[68], line 12\u001b[0m\n\u001b[1;32m 8\u001b[0m d \u001b[38;5;241m=\u001b[39m sum_vals(a, b)\n\u001b[1;32m 10\u001b[0m \u001b[38;5;66;03m# this will fail, as we are out of the scope for this variable \u001b[39;00m\n\u001b[1;32m 11\u001b[0m \u001b[38;5;66;03m# that will live and die during the function execution:\u001b[39;00m\n\u001b[0;32m---> 12\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mlocal_sum_variable\u001b[49m)\n", + "\u001b[0;31mNameError\u001b[0m: name 'local_sum_variable' is not defined" + ] + } + ], "source": [ "def sum_vals(a, b):\n", " local_sum_variable = a + b\n", @@ -1423,7 +1521,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 71, "id": "caf034e7", "metadata": { "slideshow": { @@ -1435,7 +1533,8 @@ "name": "stdout", "output_type": "stream", "text": [ - "3\n" + "2\n", + "[1]\n" ] } ], @@ -1444,14 +1543,15 @@ "\n", " # This will not fail. However, it should be avoided in general! it makes running the function\n", " # implicitely relying on code in the rest script.\n", - " print(a_var_not_passed)\n", + " print(a_var_not_passed.pop())\n", " return a + b\n", "\n", "\n", - "a_var_not_passed = 3\n", + "a_var_not_passed = [1, 2]\n", "a = 1\n", "b = 2\n", - "d = sum_vals(a, b)" + "d = sum_vals(a, b)\n", + "print(a_var_not_passed)" ] }, { @@ -1499,7 +1599,7 @@ }, { "cell_type": "markdown", - "id": "e8b536d5", + "id": "3f88965b", "metadata": { "slideshow": { "slide_type": "subslide" @@ -1511,7 +1611,7 @@ }, { "cell_type": "markdown", - "id": "bedcbdf1", + "id": "b4d6c1ee", "metadata": {}, "source": [ "Many times you will import functions from external modules, like `random`. the functions docs give you all the information you need about how to use the function:" @@ -1520,7 +1620,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "486b2f25", + "id": "83b5a560", "metadata": {}, "outputs": [], "source": [ diff --git a/practicals/Practicals_0.1.ipynb b/practicals/Practicals_0.1.ipynb index 080d2d1..1fc70e4 100644 --- a/practicals/Practicals_0.1.ipynb +++ b/practicals/Practicals_0.1.ipynb @@ -225,7 +225,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 4, "id": "614e9c24", "metadata": {}, "outputs": [ @@ -235,7 +235,7 @@ "'The'" ] }, - "execution_count": 10, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } @@ -251,7 +251,11 @@ "first_word = word_list[0]\n", "\n", "word_len_dict = {word_list[0]: len(word_list[0]),\n", - " word_list[1]: ...}\n", + " word_list[1]: len(word_list[1]),\n", + " word_list[2]: len(word_list[2])}\n", + "\n", + "# Alternative solution with loop:\n", + "word_len_dict = {word: len(word) for word in word_list}\n", "word_list[0]" ] }, @@ -265,7 +269,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 3, "id": "61ae9855", "metadata": {}, "outputs": [ @@ -276,7 +280,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[0;32mIn[13], line 5\u001b[0m\n\u001b[1;32m 2\u001b[0m word_tuple \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mtuple\u001b[39m(word_list)\n\u001b[1;32m 4\u001b[0m \u001b[38;5;66;03m# Can you change the first element of the tuple? Can you try appending new values? Can you use the +/* operators? \u001b[39;00m\n\u001b[0;32m----> 5\u001b[0m \u001b[43mword_tuple\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnewword\u001b[39m\u001b[38;5;124m\"\u001b[39m\n", + "Cell \u001b[0;32mIn[3], line 5\u001b[0m\n\u001b[1;32m 2\u001b[0m word_tuple \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mtuple\u001b[39m(word_list)\n\u001b[1;32m 4\u001b[0m \u001b[38;5;66;03m# Can you change the first element of the tuple? Can you try appending new values? Can you use the +/* operators? \u001b[39;00m\n\u001b[0;32m----> 5\u001b[0m \u001b[43mword_tuple\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnew_word\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;66;03m# try changing the values will result in a value error\u001b[39;00m\n", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } @@ -286,7 +290,7 @@ "word_tuple = tuple(word_list)\n", "\n", "# Can you change the first element of the tuple? Can you try appending new values? Can you use the +/* operators? \n", - "word_tuple[0] = \"newword\"" + "word_tuple[0] = \"new_word\" # try changing the values will result in a value error" ] }, { @@ -349,21 +353,10 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 5, "id": "885efb60", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Ellipsis" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "# Use sets operations to find the a place that might fit the preferences of Mark, Melissa and Mattew:\n", "mark_top_three = [\"PutipĆ¹\", \"Pizzangolo\", \"Christian\"]\n", @@ -371,12 +364,14 @@ "mattew_top_three = [\"Christian\", \"PutipĆ¹\", \"Pizzangolo\"]\n", "\n", "# First, convert all the lists in sets:\n", - "...\n" + "mark_set = set(mark_top_three)\n", + "melissa_set = set(melissa_top_three)\n", + "mattew_set = set(mattew_top_three)" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 6, "id": "f2f6be93", "metadata": {}, "outputs": [ @@ -386,16 +381,13 @@ "{'Christian'}" ] }, - "execution_count": 24, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Then, think about the correct set operation that will give you their overlapping choices:\n", - "mark_set = set(mark_top_three)\n", - "melissa_set = set(melissa_top_three)\n", - "mattew_set = set(mattew_top_three)\n", "\n", "common_mark_melissa = mark_set.intersection(melissa_set)\n", "common_mark_mattew = mark_set.intersection(mattew_set)\n", diff --git a/practicals/Practicals_0.2.ipynb b/practicals/Practicals_0.2.ipynb index b2363cc..612cdf0 100644 --- a/practicals/Practicals_0.2.ipynb +++ b/practicals/Practicals_0.2.ipynb @@ -362,9 +362,7 @@ " if firing_rate > 5:\n", " high_firing_rate_list.append(neuron_id)\n", "\n", - "high_firing_rate_list\n", "# Check if neuron_5 is in that list:\n", - "\n", "\"neuron_5\" in high_firing_rate_list" ] } diff --git a/practicals/Practicals_0.3.ipynb b/practicals/Practicals_0.3.ipynb index 8fe5f9e..c269aa4 100644 --- a/practicals/Practicals_0.3.ipynb +++ b/practicals/Practicals_0.3.ipynb @@ -28,22 +28,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "id": "2398af5f", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n" + ] + } + ], "source": [ "# Write a while loop over integer numbers incrementing the i \n", "# variably by one at every iteration, and stop when i\n", "# is a multiple of both 10 and 12:\n", + "i = 1\n", "\n", - "\n", - "\n" + "while True:\n", + " if i % 10 == 0 and i % 12 == 0:\n", + " break\n", + " i += 1\n", + "print(i)" ] }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 5, "id": "5672c982", "metadata": {}, "outputs": [ @@ -51,7 +63,8 @@ "name": "stdout", "output_type": "stream", "text": [ - "A random int: 4\n" + "A random int: 9\n", + "A random float: 7.043135030412195\n" ] } ], @@ -75,21 +88,44 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 22, "id": "d0c106bb", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "tail\n" + ] + } + ], "source": [ "# Use random number generators with uniform probability and if conditional to write \n", - "# a program that prints \"heads\" with probability 1/3 and \"tail\" with probability 2/3:\n" + "# a program that prints \"heads\" with probability 1/3 and \"tail\" with probability 2/3:\n", + "\n", + "p_heads_happening = 1/3\n", + "\n", + "if random.uniform(0, 1) < p_heads_happening:\n", + " print(\"heads\")\n", + "else:\n", + " print(\"tail\")\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "id": "899b5706", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number watched: 6\n" + ] + } + ], "source": [ "# Create a Netflix session simulator using a while loop and conditionals.\n", "\n", @@ -102,44 +138,131 @@ "\n", "# At the end, print out the number of episodes watched in a session!\n", "\n", - "\n" + "min_score_for_keep_watching = 3\n", + "max_score = 10\n", + "\n", + "episode_score = random.randint(0, max_score)\n", + "n_episodes_watched = 1\n", + "\n", + "while episode_score > min_score_for_keep_watching:\n", + " episode_score = random.randint(0, max_score)\n", + "\n", + " n_episodes_watched += 1\n", + " \n", + "print(f\"Number watched: {n_episodes_watched}\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, + "id": "5d3e9134", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number watched: 21\n" + ] + } + ], + "source": [ + "# Alternative solution with break:\n", + "min_score_for_keep_watching = 3\n", + "max_score = 10\n", + "\n", + "n_episodes_watched = 0\n", + "while True:\n", + " n_episodes_watched += 1\n", + " episode_score = random.randint(0, max_score)\n", + " if episode_score < min_score_for_keep_watching:\n", + " break\n", + "\n", + "print(f\"Number watched: {n_episodes_watched}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 54, "id": "35703d6b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number watched: 7\n" + ] + } + ], "source": [ "# Now we will improve the simulator adding a cliffhanger effect.\n", "# if the episode is really crappy, but there's an big cliffhanger\n", "# (probability of a cliffhanger: 1 out of 5), you keep watching anyway!\n", "\n", "# Rewrite below the while loop, but now define a cliffhanger variable.\n", - "# that is True with probability 1/5 and can make you stay in the loop:" + "# that is True with probability 1/5 and can make you stay in the loop:\n", + "\n", + "# Alternative solution with break:\n", + "min_score_for_keep_watching = 3\n", + "max_score = 10\n", + "cliffhanger_prob = 1/5\n", + "\n", + "n_episodes_watched = 0\n", + "while True:\n", + " n_episodes_watched += 1\n", + " episode_score = random.randint(0, max_score)\n", + " \n", + " has_cliffhanger = random.uniform(0, 1) < cliffhanger_prob\n", + " \n", + " if episode_score < min_score_for_keep_watching and not has_cliffhanger:\n", + " break\n", + "\n", + "print(f\"Number watched: {n_episodes_watched}\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 88, "id": "cc41ec3f", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "0.02585" + ] + }, + "execution_count": 88, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Use a for loop to run the simulator many times (like, 100? 1000?)\n", "# Each time, append to a list the result of the session (the number of episodes watched).\n", - "n_simulations = 1000\n", + "n_simulations = 100000\n", "\n", "n_watched_episodes_list = []\n", "\n", "\n", "for session in range(n_simulations):\n", - " ...\n", + " n_episodes_watched = 0\n", + " while True:\n", + " n_episodes_watched += 1\n", + " episode_score = random.randint(0, max_score)\n", + "\n", + " has_cliffhanger = random.uniform(0, 1) < cliffhanger_prob\n", + "\n", + " if episode_score < min_score_for_keep_watching and not has_cliffhanger:\n", + " break\n", + "\n", + " n_watched_episodes_list.append(n_episodes_watched)\n", "\n", "\n", "# Then, use this results list to estimate the probability of watching\n", - "# more than 15 episodes in a session:" + "# more than 15 episodes in a session:\n", + "sum([n > 15 for n in n_watched_episodes_list]) / len(n_watched_episodes_list)" ] }, { @@ -287,7 +410,6 @@ "# make sure they stick to the principles we have\n", "# been introducing:\n", "# - meaningful variable names\n", - "# - no magic numbers\n", "# - non-duplicated, readable code\n", "#\n", "# Make also sure all functions have an informative docstring \n",