{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": { "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "# Exercises" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "::: {note}\n", "You don't need to worry about using Interactive Jupyter Notebooks for these exercises. You can simply ignore the rocket icon ({fa}`rocket`) and go ahead to answer the questions using the knowledge you've gained from the chapter. Have fun!\n", "::: " ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-import\n", "#import json\n", "#from jupyterquiz import display_quiz\n", "#load all questions json file\n", "#with open(\"01.json\", \"r\") as file:\n", "# questions = json.load(file)\n", "\n", "#questions = [[q] for q in questions]" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "su7ODKnqB7tv", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.1.1\n", "\n", "In the code cell bellow you can see a function that finds the greatest common divisor of any two numbers using the math module. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "collapsed": true, "id": "YjB37kkNGsr9", "outputId": "36e77aac-9e26-4c63-fbf5-e030e5539ab1" }, "outputs": [], "source": [ "import math\n", "\n", "def find_greatest_common_divisor(a, b):\n", " greatest_common_divisor = math.gcds(a, b)\n", " return greatest_common_divisor\n", "\n", "print('The greatest common divisor is:', find_greatest_common_divisor(2, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-1-1\n", "#display_quiz(questions[0])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "aaxayx2RH9IM", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## (Searching) Exercise 2.1.2\n", "\n", "We can only take and store measurements at a limited number of locations and/or times. But what if we are interested in a value in between, i.e., at a location/time where we do not have a measurement? Then we can use interpolation to estimate that value. A popular, and simple, interpolation technique is linear interpolation. \n", "Your task is to use the module scipy to perform a 1D linear interpolation between a set of known points, where x_known and y_known are arrays with the measured $x$ and $y$ values. Use Google to look up the 1D interpolation function in scipy.

In the code below there is something missing after `return` (look the three dots). What should be the correct missing code for the function to give us the desired result?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "id": "ZazhpxxTIzxE" }, "outputs": [], "source": [ "from scipy import interpolate\n", "\n", "def interpolate_inbetween(x_known, y_known, x_predict):\n", " f = interpolate.interp1d(x_known, y_known)\n", " return ...\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-1-2\n", "#display_quiz(questions[1])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "Ue4CKV8PKnBG", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## (Searching) Exercise 2.1.3\n", "\n", "Now, let's try to measure the running time of a function, for that we will need the time module. Use it to measure the working time of the cool_function() below." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "id": "C1aOizjOK7sl", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "outputs": [], "source": [ "# you do not need to change anything in this cell\n", "def cool_function():\n", " x = 0\n", " for i in range(100000000):\n", " x += 1\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Which of the following functions will give us the working time of the cool_function()?" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "* **Option A**\n", "```python\n", "def measure_time(func):\n", " t0 = time.time()\n", " t1 = time.time()\n", " return t1 - t0\n", "```\n", "\n", "* **Option B**\n", "```python\n", "def measure_time(func):\n", " t0 = time.time()\n", " func()\n", " t1 = time.time()\n", " return t1 - t0\n", "```\n", "* **Option C**\n", "```python\n", "def measure_time(func,t0,t1):\n", " t0 = time.time()\n", " func()\n", " t1 = time.time()\n", " return func\n", "```\n", "\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-1-3\n", "#display_quiz(questions[2])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "su7ODKnqB7tv", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.2.1\n", "\n", "One of the most crucial applications of if statements is filtering the data from errors and checking whether an error is within a certain limit.\n", "\n", "For example, checking whether the difference between an estimated value and the actual value are within a certain range.\n", "\n", "Mathematically speaking, this can be expressed as $|\\hat{y} - y| < \\epsilon$\n", "\n", "where $\\hat{y}$ is your estimated value, $y$ is the actual value and $\\epsilon$ is a certain error threshold.\n", "\n", "The function check_error_size() below must do the same — it should return True if the error is within the acceptable range eps and False if it is not." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "``` python \n", "def check_error_size(estimated_value, true_value, eps):\n", " if abs(estimated_value - true_value) <= eps:\n", " return True\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-2-1\n", "#display_quiz(questions[3])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "HH2SHjK9rypL", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.2.2\n", "\n", "You have used the knowledge obtained to write your very own function to classify soil samples based on the average grain size.\n", "\n", "``` python\n", "def classify_soil(avg_grain_size):\n", " if avg_grain_size < 0.002:\n", " return 'Clay'\n", " elif avg_grain_size >= 0.002 and avg_grain_size < 0.063:\n", " return 'Silt'\n", " elif avg_grain_size >= 0.063 and avg_grain_size < 2:\n", " return 'Sand'\n", " elif avg_grain_size >= 2:\n", " return 'Gravel'\n", "\n", "print(classify_soil(1.5))\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-2-2\n", "#display_quiz(questions[4])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "TcZ--kZgtX4f", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## (Searching) Exercise 2.2.4\n", "\n", "Conditional expression is a way how one can compress an if statement to a more compact (and logical) statement. Your task is to rewrite the below if statement by using the 'conditional expression' technique." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "id": "l8fBsW3ea-Ko", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "outputs": [], "source": [ "y = 0\n", "x = 5\n", "\n", "if x % 2 == 0:\n", " y = x ** 2\n", "else:\n", " y = x % 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-2-4\n", "#display_quiz(questions[5])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "su7ODKnqB7tv", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.4.1\n", "\n", "The function `celsius_to_fahrenheit` is not working properly, can you detect the error?\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "id": "ldeM_71XgK--", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "outputs": [], "source": [ "def celsius_to_fahrenheit(temp_celsius):\n", " temp_fahrenheit = 0\n", " for i in range(len(temp_celsius)):\n", " temp_fahrenheit.append(temp_celsius[i] * 9 / 5 + 32) \n", " return temp_fahrenheit\n", "\n", "temp_celsius = [-1, -1.2, 1.3, 6.4, 11.2, 14.8, 17.8, 17.7, 13.7, 8.5, 4.1, 0.9]\n", "print(celsius_to_fahrenheit(temp_celsius))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-4-1\n", "#display_quiz(questions[6])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "GFziFh2Misx_", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.4.3\n", "\n", "Here you need to write a function that is able to sort any list consisting only of real numbers, in the descending order. For example, the list $[19, 5, 144, 6]$ becomes $[144, 19, 6, 5]$. However there are three possible options to complete correctly the code where the dots `...` are placed.\n", "\n", "``` python\n", "def sort_list(unsorted_list):\n", " return sorted(unsorted_list)...\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-4-3\n", "#display_quiz(questions[7])" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "hp6H5nvkjZLg", "nbgrader": { "grade": false, "locked": true, "solution": false } }, "source": [ "## Exercise 2.4.5\n", "\n", "In this exercise you will perform downsampling of a provided 'regular' 2D list. Downsampling is a procedure where only a subset of the data is sampled (to reduce its size, for example). Below a visual aid of what downsampling of a 2D list is. Instead of using all the data available, your task is to downsample the 2D list to keep only the data of every $a$-th row and every $b$-th column, including the first element $(a_{0,0})$.

$$A = \\left[\\begin{array}{ccccc}\n", "a_{0,0} & \\dots & a_{0,b} & \\dots & a_{0,2b} & \\dots & \\dots & a_{0,nb}\t& \\dots\\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\\\\\n", "a_{a,0} & \\dots & a_{a,b} & \\dots & a_{a,2b} & \\dots & \\dots & a_{a,nb}\t& \\dots\\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\\\\\n", "a_{2a,0} & \\dots & a_{2a,b} & \\dots & a_{2a,2b} & \\dots & \\dots & a_{2a,nb}\t& \\dots\\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\\\\\n", "a_{ma,0} & \\dots & a_{ma,b} & \\dots & a_{ma,2b} & \\dots & \\dots & a_{ma,nb} & \\dots \\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots & \\vdots\n", "\\end{array}\\right]$$\n", "\n", "Notice the `...` you need to fill with the correct code. Additionally there are some errors in the functions can you detect the errors? " ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "* **Option A**\n", "```python\n", "\n", "def downsample(data, a, b):\n", " downsample_data = [0]\n", " \n", " for i in range(len(data)):\n", " row = []\n", " # create a for loop over len(data[i]), which is the number of columns\n", " for ...\n", " if i % a == 0 and j % b == 0:\n", " row.append(data[i][j])\n", " if len(row) > 0:\n", " downsample_data.append(row)\n", " \n", " return downsample_data\n", "\n", "```\n", "\n", "* **Option B**\n", "```python\n", "\n", "def downsample(data, a, b):\n", " downsample_data = []\n", "\n", " for i in range(len(data)):\n", " row = []\n", "\n", " # create a for loop over len(data[i]), which is the number of columns\n", " for ...\n", " if i % a == 0 and j % b == 0:\n", " row.append(data[i][j])\n", " if len(row) > 0:\n", " downsample_data.append(row)\n", " \n", " return downsample_data\n", "```\n", "* **Option C**\n", "```python\n", "\n", "def downsample(data, a, b):\n", " downsample_data = 0\n", " \n", " for i in range(len(data)):\n", " row = []\n", " # create a for loop over len(data[i]), which is the number of columns\n", " for ...\n", " if i % a == 0 and j % b == 0:\n", " row.append(data[i][j])\n", " if len(row) > 0:\n", " downsample_data.append(row)\n", " \n", " return downsample_data\n", "\n", "```\n", "\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-input" ] }, "outputs": [], "source": [ "# jupyterquiz-exercise-2-4-5\n", "#display_quiz(questions[8])" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "Python_2_1.ipynb", "provenance": [] }, "kernelspec": { "display_name": "mude", "language": "python", "name": "python3" }, "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.11.9" } }, "nbformat": 4, "nbformat_minor": 1 }