{ "cells": [ { "cell_type": "markdown", "id": "9965f1b0", "metadata": { "nbgrader": { "grade": false, "grade_id": "cell-3b587ecf818e3119", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "# Exercises\n", "\n", "Each exercise carries the difficulty level indication:\n", "- [*] Easy\n", "- [**] Moderate\n", "- [***] Advanced\n", "\n", "The highest difficulty level is meant for students who wish to challenge themselves and/or have previous experience in programming." ] }, { "cell_type": "markdown", "id": "8c5d1266", "metadata": {}, "source": [ "`````{exercise} [*] Calling functions\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/01_Calling_functions.py>`\n", "\n", "Using the given function which calculates the mean, find the list which has the\n", "highest mean and the value of that mean. Using the function we do not need to \n", "write the logic of calculating the mean again for every list, but instead we put \n", "the logic in one function and re-use the same function for every list.\n", "\n", "As always, draft the pseudocode before you start coding in Python.\n", "\n", "Hint: use a for loop and track the highest mean.\n", "\n", "```\n", "list1 = [3, 5, 7, 9, 2, 4, 6, 8, 10, 1, 3, 5]\n", "list2 = [7, 9, 2, 4, 7, 5, 3, 1, 8, 6]\n", "list3 = [2, 4, 6, 9, 10, 3, 5, 6, 9]\n", "list4 = [1, 3, 5, 7, 9, 1, 3, 5, 7, 2, 4, 6, 8, 10]\n", "list5 = [4, 6, 8, 10, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]\n", "\n", "numbers_lists = [list1, list2, list3, list4, list5]\n", "\n", "\n", "def calculate_mean(list_numbers):\n", " sum = 0\n", " for i in list_numbers:\n", " sum += i\n", " return sum / len(list_numbers)\n", "\n", "\n", "# Your code here\n", "```\n", "`````" ] }, { "cell_type": "markdown", "id": "da9f4d8b", "metadata": {}, "source": [ "`````{exercise} [*] BMI\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/02_BMI.py>`\n", "\n", "Body mass index (BMI) can be calulated as: \n", "$BMI = weight / height^2$\n", "\n", "**Exercise A**: Calculate the BMI of various people using a `for` loop and return\n", "BMIs as a list.\n", "\n", "```\n", "weights = [60, 76, 55, 90]\n", "heights = [1.70, 1.80, 1.65, 1.90]\n", "\n", "bmi = []\n", "\n", "# Your code here\n", " \n", "print(bmi)\n", "```\n", "\n", "\n", "**Exercise B**: Imagine later we want to calculate the BMI of another list of people. \n", "We could copy the code, but if we want to do this more often it is better to \n", "write a function and avoid code duplication. \n", "\n", "Rewrite the code into a function called `calculate_bmi`, then call the function\n", "and save the output in the variable `bmi`. Finally, print the results.\n", "\n", "```\n", "weights = [60, 76, 55, 90]\n", "heights = [1.70, 1.80, 1.65, 1.90]\n", "\n", "def calculate_bmi( # Your code here):\n", " # Your code here\n", " return # Your code here\n", "\n", "bmi = calculate_bmi( # Your code here)\n", "\n", "print(bmi)\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "247cea5f", "metadata": {}, "source": [ "`````{exercise} [*] Local vs. global\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/16_Local_global.py>`\n", "\n", "This exercise will help you understand the difference between local and global variables in Python. You will see how variable scope affects the behavior of your code. You will be given a block of code. Pay attention to how variables are used and modified. Run the code and observe the output.\n", "\n", "```\n", "counter = 10\n", "\n", "def increment_counter():\n", " counter = 5 # Local variable\n", " counter += 1\n", " print(\"Inside function, counter:\", counter)\n", "\n", "increment_counter()\n", "print(\"Outside function, counter:\", counter)\n", "```\n", "\n", "Now modify the function `increment_counter` so that it uses the global variable counter instead of creating a local variable.\n", "\n", "```\n", "# Your altered code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "6948dda0", "metadata": {}, "source": [ "`````{exercise} [**] Motif finding\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/03_Motif.py>`\n", "\n", "It's often useful to know if a given DNA sequence contains a specific \n", "motif: in Python, a variable should be `True` if the motif is found \n", "and `False` otherwise. DNA sequences are strings composed of the characters \n", "A, T, C, and G. A motif is a specific sequence of these characters. \n", "This is an example of how you can find this:\n", "\n", "```\n", "dna_sequence = \"ATGCGATACGCTTGA\"\n", "motif = \"GCT\"\n", "\n", "if motif in dna_sequence:\n", " found = True\n", "else:\n", " found = False\n", "\n", "print(\"Motif found:\", found)\n", "```\n", "\n", "We might want to do this for multiple DNA sequences or multiple motifs, and \n", "different combinations of these. This is where functions come in: with functions, \n", "this logic can easily be applied to any combination of DNA sequences and motifs.\n", "\n", "```\n", "dna_sequence = \"ATGCGATACGCTTGA\"\n", "motif = \"GCT\"\n", "\n", "def find_motif(dna, motif):\n", " found = False\n", " \n", " # Your code here\n", " \n", " return found\n", "\n", "found = find_motif(dna_sequence, motif)\n", "\n", "print(\"Motif found:\", found)\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "495380c8", "metadata": {}, "source": [ "`````{exercise} [**] Gravity\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/04_Gravity.py>`\n", "\n", "In this exercise we write a function to calculate the gravitational force. \n", "The gravitational force is given by the following formula:\n", "\n", "$F_g = \\frac{G * m_1 * m_2}{r^2}$\n", "\n", "**Exercise A**: \n", "Imagine we want to make a function which calculates the gravity on Earth.\n", "Let's call this funcion `gravity_earth`.\n", "Which of the variables become constants and which should be input parameters?\n", "\n", "Hint: You will need to Google to find the required constant values for this \n", "function.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise B**:\n", "Apply your function (`gravity_earth`) to calculate the gravitational force on an \n", "object with mass of 10 kg. \n", "\n", "The solution should be 98.1 N.\n", "\n", "```\n", "m = 10 # kg\n", "\n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise C**:\n", "Imagine we want to compare the gravitational force an astronaut experiences on \n", "different planets. Given that the astronaut weighs 90 kg, write a function \n", "which calculates the gravitational force on the astronaut on different planets.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "2bd44cd3", "metadata": {}, "source": [ "`````{exercise} [*] Mutable parameters\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/05_Mutable_parameters.py>`\n", "\n", "In this exercise, you will explore how variables behave when passed to a \n", "function, and how mutating a list (which is a mutable object) inside a function\n", "affects the original list defined outside the function. You will also observe \n", "the behavior of immutable objects such as integers and strings when passed to a \n", "function.\n", "\n", "\n", "You are given a list of cell counts from different biological samples. \n", "The function you will implement will add a new value to this list to update it \n", "with new data. \n", "Additionally, the function will attempt to modify an integer variable, but \n", "notice the difference in behavior between the mutable list and the immutable \n", "integer.\n", "\n", "We have a function `update_sample` that:\n", "* Appends a new value to a list of cell counts (this list is defined outside \n", "the function).\n", "* Attempts to modify a variable (an integer) defined outside the function.\n", "\n", "After running this code, observe the behavior of the list and the integer \n", "variable outside the function.\n", "\n", "```\n", "# Global list (mutable) and integer (immutable) defined outside the function\n", "cell_counts = [100, 120, 130]\n", "total_samples = 3\n", "\n", "def update_sample(new_count, cell_counts = cell_counts, total_samples = total_samples):\n", " # Add new sample count to the list (mutable object)\n", " cell_counts.append(new_count)\n", " \n", " # Attempt to modify total_samples (immutable object)\n", " total_samples += 1 # This will not affect the global variable!\n", "\n", "# Call the function with a new sample count\n", "update_sample(150)\n", "\n", "# Print the list and the integer outside the function\n", "print(\"Updated cell counts:\", cell_counts) # Expected to be updated\n", "print(\"Total samples:\", total_samples) # Expected to NOT be updated\n", "\n", "assert cell_counts == [100, 120, 130, 150], \"cell counts should be updated\"\n", "assert total_samples == 4, \"total samples should be updated\"\n", "```\n", "\n", "\n", "Why is the list `cell_counts` updated, but `total_samples` does not change?\n", "Modify the code to fix the behavior of `total_samples` so that it updates correctly. \n", "\n", "Hint: You might need to use the global keyword or return the updated value from \n", "the function.\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "36d31c2b", "metadata": {}, "source": [ "`````{exercise} [**] Reverse complement\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/06_Reverse_complement.py>`\n", "\n", "In this exercise we will create a function which returns the reverse complement\n", "of a DNA sequence. This is a useful case to create a function as finding the \n", "reverse complement of any sequence follows the same logic, so instead of \n", "copy-pasting the code, we create a function and call it every time we need to \n", "find the reverse complement of a sequence. \n", "\n", "The function should be able to find the reverse complement of any DNA sequence \n", "(so also for varying lengths). Name the function `reverse_complement`.\n", "You can assume that DNA consists only of A, T, C and G.\n", "\n", "After you've defined the function, call it for the given DNA sequence and print \n", "the output.\n", "\n", "Example of a reverse complement:\n", "\n", "DNA: ACCTGTAAA \\\n", "Reverse Complement: TTTACAGGT\n", "\n", "Hint: A list or string can be reversed using `reversed_var = var_name[::-1]`\n", "\n", "```\n", "DNA = \"TTGTGATATAGGTACCAGTCACGTTGACGTAGTCTAGCTAGCATGTCAAGCACTTGAA\"\n", "\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "834ef933", "metadata": {}, "source": [ "`````{exercise} [**] Documenting functions\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/07_Documenting.py>`\n", "\n", "**Note**: this exercise contains an introduction, which is absent from the downloadable exercise (`.py`) file.\n", "\n", "````{admonition} Introduction\n", ":class: note, dropdown\n", "\n", "When learning how to code it is not only important how to make code that works,\n", "but also that the code is **understandable**. This is important in collaborations \n", "and even in solo projects (since after a while you can get confused with your \n", "own code which you wrote earlier). Generally, this is done with comments throughout \n", "your code, but there are two ways which are specific to functions: \n", "docstrings and type hints. \n", "\n", "A **docstring** is a special kind of comment in Python used to describe what a function does. It is placed directly below the function definition and enclosed in triple quotes (\"\"\"). \n", "A well-written docstring typically includes:\n", "\n", "* A brief description of what the function does.\n", "* Information about the parameters the function takes (names, types, and descriptions).\n", "* A description of the return value, including its type.\n", "* Any exceptions that the function might raise (if applicable).\n", "\n", "Example of a docstring:\n", "\n", "```\n", "def add(a, b):\n", " \"\"\"\n", " Adds two numbers together.\n", "\n", " Parameters:\n", " a (int or float): The first number.\n", " b (int or float): The second number.\n", "\n", " Returns:\n", " int or float: The sum of the two numbers.\n", " \"\"\"\n", " return a + b\n", "\n", "```\n", "\n", "\n", "**Type hints** (also called type annotations) are a way to explicitly specify the data types of variables, function parameters, and return values. They help in improving code readability and can assist tools that perform type checks, which can catch potential errors before running the code.\n", "\n", "Type hints do not affect how the code runs, but they provide additional information for the developer and anyone reviewing the code.\n", "\n", "Example:\n", "\n", "```\n", "def add(a: int, b: int) -> int:\n", " \"\"\"\n", " Adds two integers together.\n", "\n", " Parameters:\n", " a (int): The first integer.\n", " b (int): The second integer.\n", "\n", " Returns:\n", " int: The sum of the two integers.\n", " \"\"\"\n", " return a + b\n", "\n", "```\n", "\n", "In this example:\n", "\n", "The parameters `a` and `b` are expected to be of type `int`.\n", "The function is expected to return a value of type `int`.\n", "\n", "````\n", "\n", "In this exercise, we work with a function that calculates a person's \n", "heart rate training zones based on their age and resting heart rate. The \n", "function uses the Karvonen formula to calculate the target heart rate zones \n", "for light, moderate, and intense exercise.\n", "\n", "The formula is:\n", "\n", "Target_HR = Resting_HR + (Maximum_HR − Resting_HR) × Intensity\n", "\n", "where:\n", "\n", "Maximum_HR = 220−age\n", "\n", "Intensities: light (50%), moderate (70%), intense (85%).\n", "\n", "\n", "**Exercise A**:\n", "Add the correct type hints and create a docstring for the function given. \n", "\n", "Your type hints should be the same as those given in the solution. \n", "For the docstring it is mostly important to see if it contains the \n", "same elements; the wording will usually be different per programmer.\n", "\n", "```\n", "def calculate_heart_rate_zones(age, resting_hr):\n", "\n", " max_hr = 220 - age\n", " \n", " # Intensities for light, moderate, and intense exercises\n", " intensities = [0.50, 0.70, 0.85]\n", " \n", " heart_rate_zones = []\n", " \n", " for intensity in intensities:\n", " heart_rate_zones.append(resting_hr + (max_hr - resting_hr) * intensity)\n", " \n", " return heart_rate_zones\n", "\n", "\n", "# Example input parameters\n", "age_of_person = 30 # years\n", "resting_heart_rate = 60.0 # beats per minute\n", "\n", "# Call the function with the example inputs\n", "heart_rate_zones = calculate_heart_rate_zones(age_of_person, resting_heart_rate)\n", "\n", "# Print the result\n", "print(\"Heart Rate Zones:\", heart_rate_zones)\n", "```\n", "\n", "\n", "Docstrings are not only useful as a summary when looking directly at the source code, but also when using functions when not looking at the source code. \n", "We can then access docstrings using Python's `help` function.\n", "\n", "**Exercise B**: \n", "Call the `help` function on the function that you just created the docstring for \n", "and your docstring should be displayed.\n", "\n", "Note: you can also do this with functions you have not created yourself, e.g.:\n", "\n", "```\n", "import numpy as np\n", "help(np.linspace)\n", "```\n", "\n", "```\n", "help(# Your code here)\n", "``` \n", "\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "0a836fc6", "metadata": {}, "source": [ "`````{exercise} [*] Hardcoding - cell count threshols\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/08_Hardcoding_cell_count.py>`\n", "\n", "\n", "One mistake which is often made in code in general, but also in functions \n", "specifically (since functions especially are designed to be generic and \n", "flexible), is hardcoding. This is where one variable is set to a specific \n", "value, which restricts the use cases of a particular piece of code.\n", "\n", "In this exercise, you are provided with code that determines whether a \n", "sample contains a sufficient number of cells for a study. The code is hardcoded \n", "to check if the sample contains at least 100 cells, which works for some \n", "studies but not for others. Modify the code such that it would also work for \n", "studies which have different thresholds.\n", "\n", "```\n", "def is_sufficient_cells(cell_count):\n", " # Hardcoded threshold for 100 cells\n", " if cell_count >= 100:\n", " return True\n", " else:\n", " return False\n", "\n", "# Example 1: Study with 100 cell threshold (works fine)\n", "sample_cell_count = 120\n", "print(\"Is the sample sufficient?\", is_sufficient_cells(sample_cell_count))\n", "\n", "# Example 2: Study with 200 cell threshold (doesn't work correctly)\n", "print(\"Is the sample sufficient for a study requiring 200 cells?\", is_sufficient_cells(sample_cell_count))\n", "```\n", "\n", "It is important to note that not everything needs to be 100% flexible, \n", "for example, in this cases leaving the cell count hardcoded might be fine, \n", "as it might only be used by your lab which always uses the same amount, or the\n", "number is an industry standard which is always used. This makes \n", "this a consideration between flexibility and simplicity.\n", "\n", "There is also another way to solve this using default parameters, which looks like\n", "this:\n", "```\n", "def function(force, mass = 10):\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "2d010081", "metadata": {}, "source": [ "`````{exercise} [*] Hardcoding - projectile motion\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/09_Hardcoding_projectile_motion.py>`\n", "\n", "One mistake which is often made in code in general, but also in functions \n", "specifically (since functions especially are designed to be generic and \n", "flexible), is hardcoding. This is where one variable is set to a specific \n", "value, which restricts the use cases of a particular piece of code.\n", "\n", "In this exercise, you are provided with code that calculates the maximum height \n", "of a projectile based on a fixed gravitational acceleration. The code works \n", "perfectly on Earth, but fails on other planets like Mars or Jupiter, where the \n", "gravitational constant differs. Your task is to modify the code to work in any \n", "scenario by fixing the hardcoded gravitational constant.\n", "\n", "The formula for the maximum height of a projectile is:\n", "\n", "$h_{max} = \\frac{v_0^2 sin^2(\\theta)}{2g}$\n", "\n", "Where:\n", "* $v_0$ is the initial velocity\n", "* $\\theta$ is the launch angle (in degrees)\n", "* $g$ is the gravitational acceleration\n", "\n", "```\n", "import math\n", "\n", "def max_height(v0, theta):\n", " # Hardcoded gravitational constant for Earth\n", " g = 9.81 # m / s^2\n", " theta_rad = math.radians(theta)\n", " h_max = (v0**2 * math.sin(theta_rad)**2) / (2 * g)\n", " return h_max\n", "\n", "# Example 1: Earth (works fine)\n", "initial_velocity = 50 # m/s\n", "angle = 45 # degrees\n", "print(\"Max height on Earth:\", max_height(initial_velocity, angle))\n", "\n", "# Example 2: Mars (g = 3.71 m/s², doesn't work correctly)\n", "print(\"Max height on Mars:\", max_height(initial_velocity, angle))\n", "```\n", "\n", "It is important to note that not everything needs to be 100% flexible, for \n", "example, in this case leaving the gravitational constant hardcoded might be \n", "fine, as it is highly likely you're coding something which will only ever be \n", "used on Earth and it makes the function simpler to use. This makes this a \n", "consideration between flexibility and simplicity.\n", "\n", "There is also another way to solve it using default parameters, which looks like\n", "this:\n", "```\n", "def function(force, mass = 10):\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "4a671816", "metadata": {}, "source": [ "`````{exercise} [*] Returning multiple values\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/10_Return_multiple_values.py>`\n", "\n", "In this exercise we will practice using functions that return multiple values \n", "and see how to store multiple values. One common reason to return multiple \n", "values with one function is that the outputs require the same input parameters \n", "and both output values are always required for our use case. In other cases \n", "one of the outputs might be an intermediary output of the final output, but the \n", "intermediary is still useful to us.\n", "\n", "In this example you will work with a function that calculates the perimeter and \n", "area of a rectangle. The goal is to help you understand the utility of returning \n", "multiple values from a function and how to correctly assign these values to \n", "different variables.\n", "\n", "**Exercise A**:\n", "You are provided with a function `calculate_rectangle` that calculates both the \n", "perimeter and area of a rectangle given its length and width.\n", "Your task is to call the function, capture the returned values, and correctly \n", "assign them to the variables perimeter and area.\n", "Print out the results to verify that you have correctly handled the function's output.\n", "\n", "```\n", "def calculate_rectangle(length, width):\n", " perimeter = 2 * (length + width)\n", " area = length * width\n", " return perimeter, area\n", "\n", "# Given parameters\n", "length = 5.0 # meters\n", "width = 3.0 # meters\n", "\n", "# Your code here\n", "```\n", "\n", "**Exercise B**:\n", "Do the same as in A, but with a slightly different function.\n", "\n", "```\n", "def calculate_rectangle_list(length, width):\n", " perimeter = 2 * (length + width)\n", " area = length * width\n", " return [perimeter, area]\n", "\n", "# Given parameters\n", "length = 5.0 # meters\n", "width = 3.0 # meters\n", "\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "106f23bf", "metadata": {}, "source": [ "`````{exercise} [**] Halloween route\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/11_Halloween.py>`\n", "\n", "For Halloween in your neighborhood, you get a list with adresses randomly \n", "distributed over a map. It is up to you to find the optimal route to pass \n", "by every house and walk the shortest distance overall. \n", "\n", "**Exercise A**:\n", "Make a function named `dist` which calculates the distance between the \n", "current location and a future location. \n", "\n", "Hint: you might want to use `np.sqrt`.\n", "\n", "```\n", "current_location = [0,0]\n", "future_location = [3,4] \n", "\n", "def dist (current, future):\n", "# Your code here\n", "```\n", "\n", "**Exercise B**:\n", "Now instead of getting one future location, you get an array with locations. \n", "Make a function `best_location` to find the best future location, which is \n", "closest to the current location.\n", "\n", "Hint: you might want to use `np.where`, and feel free to reuse (part of) your \n", "above `dist` function.\n", "\n", "```\n", "future_locations= np.array( [ [10,0],[10,5] , [10,-5],[-8,0], [-8,4],[-8,-4],[-2,1],[-5,2.5],[3,1.5],[7,3.5]])\n", "# print(np.shape(future_locations))\n", "\n", "def best_location(current, future):\n", "# Your code here\n", "```\n", "\n", "**Exercise C**:\n", "By using the previous `best_location` function, write code to automatically \n", "find the most optimal route along all `future_locations`. Do this by repeatedly \n", "finding the best next step. \n", "\n", "An array, called `route`, should be generated, which is the optimally \n", "rearranged version of `future_locations`, starting and ending at the current \n", "location [0,0]. Whether you are correct can be directly seen after plotting \n", "the route below. \n", "\n", "Hint: you might want to use `numpy.delete(arr, obj, axis=None)`\n", "* arr: Input array\n", "* obj: Row or column number to delete\n", "* axis: Axis to delete\n", "\n", "```\n", "def find_best_location(current,future):\n", " route = np.zeros((len(future)+2, 2))\n", " # Your code here\n", " return route\n", "```\n", "\n", "With this code you can visualize your route:\n", "\n", "```\n", "route = find_best_location(current_location, future_locations)\n", "print(route)\n", "\n", "import matplotlib.pyplot as plt\n", "\n", "plt.plot(route[:,0],route[:,1],'*-')\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "93169a6e", "metadata": {}, "source": [ "`````{exercise} [**] Black Friday\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/12_Black_Friday.py>`\n", "\n", "Functions can use multiple return statements using if-else statements. \n", "The first return encountered will be the value returned from the function.\n", "For example:\n", "\n", "```\n", "def function(x):\n", " if x >= :\n", " return ...\n", " elif x >= :\n", " return ...\n", " elif x >= :\n", " return ...\n", " return ...\n", "```\n", " \n", "**Exercise A**:\n", "In this exercise, you are calculating the total price after applying discounts.\n", "In this case the store has different applicable discounts for increasing totals:\n", "* 20% off from 50 euros \n", "* 30% off from 100 euros \n", "* 50% off from 200 euros \n", "\n", "Implement function `calculate_discount` that returns the discounted price\n", "based on the price before discount.\n", "Test your function by passing the following values to it: \n", "100, 70, 250, 30, -10\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**:\n", "Sometimes the store website does not work correctly for the store and the price before\n", "discount ends up being negative. This should not happen, so we would like the \n", "function to throw an error if the total is negative.\n", "\n", "```\n", "# Your code here\n", "\n", "\n", "# If the code was altered correctly this code line should give an error\n", "print(\"Total = \", calculate_discount(-3))\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "9fc3bf03", "metadata": {}, "source": [ "`````{exercise} [**] Roman centurion\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/13_Centurion.zip>`\n", "\n", "Imagine a cruel Roman centurion (or a very smart virus), who releases only \n", "one out of all prisoners alive. He does this by removing every $N^{th}$ prisoner, \n", "until he is left with a sole survivor. \n", "\n", "Your task is to predict, with a given number of prisoners and value for \n", "`kill_every`, which prisoner will survive.\n", "\n", "Given the number of prisoners `nb_prisoners` and the kill-every number \n", "`kill_every`, make a function which predicts which prisoner will survive.\n", "For example `nb_prisoners=10`, `kill_every=3`, results in prisoner number 4 \n", "surviving:\n", "\n", "```\n", "0 1 2 3 4 5 6 7 8 9 -> kill 2\n", "0 1 3 4 5 6 7 8 9 -> kill 5\n", "0 1 3 4 6 7 8 9 -> kill 8\n", "0 1 3 4 6 7 9 -> kill 1\n", "0 3 4 6 7 9 -> kill 6\n", "0 3 4 7 9 -> kill 0\n", " 3 4 7 9 -> kill 7\n", " 3 4 9 -> kill 4\n", " 3 9 -> kill 9\n", " 3 -> the fourth prisoner survived (note Python counts from 0)\n", "```\n", "\n", "**Exercise A**: \n", "Predict what is the best programming approach.\n", "Before you start programming, think about the easiest way to implement. \n", "Check the images below for three representations of possible Python implementations.\n", "\n", "\n", "```{figure} ../Coding_exercises/Week_3/Joyce/13_Centurion/Overactive_centurion.png\n", "---\n", "height: 350px\n", "name: cent1\n", "---\n", "```\n", "\n", "```{figure} ../Coding_exercises/Week_3/Joyce/13_Centurion/Smart_centurion.png\n", "---\n", "height: 345px\n", "name: cent2\n", "---\n", "```\n", "\n", "```{figure} ../Coding_exercises/Week_3/Joyce/13_Centurion/Lazy_centurion.png\n", "---\n", "height: 355px\n", "name: cent3\n", "---\n", "```\n", "\n", "\n", "**Exercise B**:\n", "Implement your choice of centurion.\n", "\n", "If you cannot choose, you are recommended to start with the lazy centurion (who \n", "sits down, lets the prisoners walk and kills every $N^{th}$ person).\n", "- Note that stitching of NumPy arrays is done with `np.concatenate([a,b])`.\n", "- Write pseudocode first.\n", "- Don't forget to check your intermediate answers, especially the ones in the \n", "second and third iteration. \n", "\n", "Define the number of prisoners and `kill_every` and test your function. You can try\n", "several combinations; you may want to start with `nb_prisoners=10` and `kill_every=3` from the example above.\n", "\n", "```\n", "import numpy as np\n", "\n", "def decimate(nb_prisoners, kill_every):\n", "# Your code here\n", "```\n", "\n", "**Exercise C** (Optional):\n", "Implement one or both of the other centurions.\n", "\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "2547f4f2", "metadata": {}, "source": [ "`````{exercise} [**] Central dogma\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/14_Central_dogma.zip>`\n", "\n", "In this exercise, you will work with genomic sequences using dictionaries, \n", "lists and strings.\n", "\n", "Specifically, you will write a function that compares two DNA sequences and \n", "checks for certain types of mutations.\n", "\n", "**Transcription**\n", "\n", "TFIID is a protein complex \n", "essential for the initiation of transcription by RNA Polymerase II. It \n", "contains multiple subunits, including the TATA-binding protein (TBP). \n", "TBP binds specifically to the TATA box, a DNA sequence typically found in the \n", "promoter region of many genes. This binding helps position TFIID at the correct \n", "location on the DNA, which in turn helps recruit other transcription factors and \n", "RNA Polymerase II to initiate transcription.\n", " \n", "Usually, this TATA-box sits 25 nucleotides upstream of the transcription start \n", "site. An unknown number of nucleotides later, you will find the start codon.\n", "\n", "Chemically, DNA is transcribed from 3' to 5' with respect to the template strand.\n", "In bioinformatics, the convention is to store genomic data from 5' to 3'. You \n", "may assume that the given sequence corresponds to the coding sequence. \n", "\n", "```{figure} ../Coding_exercises/Week_3/Joyce/14_Central_dogma/Transcription.png\n", "---\n", "height: 100px\n", "name: transcription\n", "---\n", "```\n", "\n", "```\n", "DNA = 'TTGTGATATAGGTACCAGTCACGTTGACGTAGTCTAGCTAGCATGTCAAGCACTTGAA'\n", "```\n", "\n", "**Exercise A**: Transcription\n", "\n", "Write a function `transcribe` that takes a DNA sequence (as string),\n", "localises the TATA-box and transcribes the gene from the transcription start \n", "site onwards, until the end of the given sequence. The output should be a string. \n", "The function should not contain any `for` loops.\n", "\n", "* Example input: 'TTGTGATATAGGTACCAGTCACGTTGACGTAGTCTAGCTAGCATGTCAAGCACTTGAA'\n", "* Example output: 'GUCUAGCUAGCAUGUCAAGCACUUGAA'\n", "\n", "Hints:\n", "- `string.find` may be useful for finding the TATA-box.\n", "- `string.replace` may be useful for replacing T with U.\n", "\n", "```\n", "def transcribe(DNA):\n", " \n", " # Your code here\n", "\n", " return RNA\n", "```\n", "\n", "\n", "**Translation**\n", "\n", "Next, the mRNA is translated in the ribosome, where all triplets are paired to \n", "the anticodons of charged tRNA. Note that translation only starts after the \n", "start codon AUG, which also corresponds to the first amino acid of the \n", "polypeptide: methionine. Since there are 64 possible codons and only 20 amino \n", "acids, we know that several codons can map onto the same amino acid.\n", "\n", "```{figure} ../Coding_exercises/Week_3/Joyce/14_Central_dogma/Translation.png\n", "---\n", "height: 100px\n", "name: translation\n", "---\n", "```\n", "\n", "\n", "**Exercise B**: Coding sequence\n", "\n", "Write a function `codingRNA` that takes this RNA transcript, finds \n", "the first start codon, finds the corresponding first stop codon and exports \n", "all triplets as a list (including stop codon). The stop codons are `UAA`, \n", "`UAG` and `UGA`. If there is no stop codon at the end, write `'no stop'` as \n", "final codon. If there is no start codon, return `[]`.\n", "\n", "* Example input 1: `'GUCUAGCUAGCAUGUCAAGCACUUGAA'`\n", "* Example output 1: `['AUG','UCA','AGC','ACU','UGA']`\n", "\n", "* Example input 2: `'GUCUAGCUAGCAUGUCAAGCACU'`\n", "* Example output 2: `['AUG','UCA','AGC','ACU','no stop']`\n", "\n", "```\n", "def codingRNA(RNA):\n", "\n", "# Your code here\n", "```\n", "\n", "**Exercise C**: Translation\n", "\n", "Write a function `translate` that takes this coding RNA array and translates it.\n", "You may use the given dictionary. The output should be a string. If there \n", "is no start codon, return ''. If there is no stop codon, add a dot at the end: \n", "'MSST.'.\n", "\n", "```\n", "conversion = {'AUA':'I', 'AUC':'I', 'AUU':'I', 'AUG':'M','ACA':'T', 'ACC':'T',\\\n", " 'ACG':'T', 'ACU':'T','AAC':'N', 'AAU':'N', 'AAA':'K', 'AAG':'K',\\\n", " 'AGC':'S', 'AGU':'S', 'AGA':'R', 'AGG':'R','CUA':'L', 'CUC':'L',\\\n", " 'CUG':'L', 'CUU':'L','CCA':'P', 'CCC':'P', 'CCG':'P', 'CCU':'P',\\\n", " 'CAC':'H', 'CAU':'H', 'CAA':'Q', 'CAG':'Q','CGA':'R', 'CGC':'R',\\\n", " 'CGG':'R', 'CGU':'R','GUA':'V', 'GUC':'V', 'GUG':'V', 'GUU':'V',\\\n", " 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCU':'A','GAC':'D', 'GAU':'D',\\\n", " 'GAA':'E', 'GAG':'E','GGA':'G', 'GGC':'G', 'GGG':'G', 'GGU':'G',\\\n", " 'UCA':'S', 'UCC':'S', 'UCG':'S', 'UCU':'S','UUC':'F', 'UUU':'F',\\\n", " 'UUA':'L', 'UUG':'L','UAC':'Y', 'UAU':'Y', 'UAA':'stop', \\\n", " 'UAG':'stop','UGC':'C', 'UGU':'C', 'UGA':'stop', 'UGG':'W'}\n", "\n", "triplet = 'AUG'\n", "print(conversion[triplet])\n", "```\n", "\n", "```\n", "def translate(codingRNAlist: list) -> str:\n", " \n", " #conversion = \n", " protein = '' # Initialise an empty protein\n", " \n", " # Your code here\n", "```\n", "\n", "\n", "**Mutation**\n", "\n", "Mutations can throw a spanner in the works with regard to protein functionality. \n", "For the purpose of this exercise, we will distinguish the following types of \n", "mutations:\n", "* Silent: mutation outside coding RNA.\n", "* Synonymous: no different amino acid sequence despite mutation in coding RNA.\n", "* Missense: single substitution in the amino acid sequence.\n", "* Nonsense: a sense codon is mutated into a stop codon, leading to early termination.\n", "* Resense: a stop codon is mutated into a sense codon, leading to extension of \n", "the protein.\n", "* Indel: alteration of reading frame by insertion or deletion (hence indel), often \n", "leading to a frameshift.\n", "\n", "\n", "**Exercise D**: Mutation checker\n", "\n", "Write a function `mutationcheck` that takes two DNA sequences and checks what \n", "type of mutation occurs (if any). Possible outputs are: `'none'`, `'silent'`, \n", "`'synonymous'`, `'missense'`, `'nonsense'` and `'resense'`. You may assume that \n", "there is only one mutated nucleotide and there are no indels. Your code should \n", "be able to handle mutations that lead to the lack of a stop codon.\n", "\n", "* Example inputs: `'TTGTGATATAGGTACCAGTCACGTTGACGTAGTCTAGCTAGCATGTCAAGCACTTGAA'`, \n", " `'TTGTGATATAGGTACCAGTCACGTTGACGTAGTCTAGCTAGCATGTCTAGCACTTGAA'`\n", "* Example output: `'synonymous'`\n", "\n", "```\n", " def mutationcheck(DNA_wildtype: str, DNA_mutation: str) -> str:\n", " \n", "# Your code here\n", "```\n", "\n", "\n", "**Point mutations in real life: Hemoglobin**\n", "\n", "In this exercise, you will apply the previously written functions to real genomic\n", "data.\n", "\n", "\n", "Red blood cells are the body's oxygen transporters. They contain an oxygen-binding \n", "protein called hemoglobin (Hb), which consists of four subunits. In adults, the \n", "most common form of Hb is hemoglobin A (HbA). It consists of two alpha and two \n", "beta globin subunits. The alpha globin subunit comes in two flavours: type 1 \n", "and type 2. You are given the mRNAs of healthy alpha 1, alpha 2, and beta globin.\n", "\n", "```\n", "alpha1globin = 'TATACTGGCGCGCTCGCGGGCCGGCACTCTTCTGGTCCCCACAGACTCAGAGAGAACCCACCATG\\\n", " GTGCTGTCTCCTGCCGACAAGACCAACGTCAAGGCCGCCTGGGGTAAGGTCGGCGCGCACGCTGGCGAGTATGGTGC\\\n", " GGAGGCCCTGGAGAGGATGTTCCTGTCCTTCCCCACCACCAAGACCTACTTCCCGCACTTCGACCTGAGCCACGGCT\\\n", " CTGCCCAGGTTAAGGGCCACGGCAAGAAGGTGGCCGACGCGCTGACCAACGCCGTGGCGCACGTGGACGACATGCCC\\\n", " AACGCGCTGTCCGCCCTGAGCGACCTGCACGCGCACAAGCTTCGGGTGGACCCGGTCAACTTCAAGCTCCTAAGCCA\\\n", " CTGCCTGCTGGTGACCCTGGCCGCCCACCTCCCCGCCGAGTTCACCCCTGCGGTGCACGCCTCCCTGGACAAGTTCC\\\n", " TGGCTTCTGTGAGCACCGTGCTGACCTCCAAATACCGTTAAGCTGGAGCCTCGGTGGCCATGCTTCTTGCCCCTTGG\\\n", " GCCTCCCCCCAGCCCCTCCTCCCCTTCCTGCACCCGTACCCCCGTGGTCTTTGAATAAAGTCTGAGTGGGCGGCA'\n", "\n", "alpha2globin = 'TATACTGGCGCGCTCGCGGCCCGGCACTCTTCTGGTCCCCACAGACTCAGAGAGAACCCACCATG\\\n", " GTGCTGTCTCCTGCCGACAAGACCAACGTCAAGGCCGCCTGGGGTAAGGTCGGCGCGCACGCTGGCGAGTATGGTGC\\\n", " GGAGGCCCTGGAGAGGATGTTCCTGTCCTTCCCCACCACCAAGACCTACTTCCCGCACTTCGACCTGAGCCACGGCT\\\n", " CTGCCCAGGTTAAGGGCCACGGCAAGAAGGTGGCCGACGCGCTGACCAACGCCGTGGCGCACGTGGACGACATGCCC\\\n", " AACGCGCTGTCCGCCCTGAGCGACCTGCACGCGCACAAGCTTCGGGTGGACCCGGTCAACTTCAAGCTCCTAAGCCA\\\n", " CTGCCTGCTGGTGACCCTGGCCGCCCACCTCCCCGCCGAGTTCACCCCTGCGGTGCACGCCTCCCTGGACAAGTTCC\\\n", " TGGCTTCTGTGAGCACCGTGCTGACCTCCAAATACCGTTAAGCTGGAGCCTCGGTAGCCGTTCCTCCTGCCCGCTGG\\\n", " GCCTCCCAACGGGCCCTCCTCCCCTCCTTGCACCGGCCCTTCCTGGTCTTTGAATAAAGTCTGAGTGGGCAGCA'\n", "\n", "betaglobin = 'TATAGGGCAGAGCCATCTATTGCTTACATTTGCTTCTGACACAACTGTGTTCACTAGCAACCTCAAA\\\n", " CAGACACCATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAA\\\n", " GTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTTGAGTCCTTTGGGGATCT\\\n", " GTCCACTCCTGATGCTGTTATGGGCAACCCTAAGGTGAAGGCTCATGGCAAGAAAGTGCTCGGTGCCTTTAGTGATG\\\n", " GCCTGGCTCACCTGGACAACCTCAAGGGCACCTTTGCCACACTGAGTGAGCTGCACTGTGACAAGCTGCACGTGGAT\\\n", " CCTGAGAACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTCACCCCACC\\\n", " AGTGCAGGCTGCCTATCAGAAAGTGGTGGCTGGTGTGGCTAATGCCCTGGCCCACAAGTATCACTAAGCTCGCTTTC\\\n", " TTGCTGTCCAATTTCTATTAAAGGTTCCTTTGTTCCCTAAGTCCAACTACTAAACTGGGGGATATTATGAAGGGCCT\\\n", " TGAGCATCTGGATTCTGCCTAATAAAAAACATTTATTTTCATTGCAA'\n", "```\n", "\n", "Note that we have edited the sequences slightly to make the exercise easier. For \n", "instance, we removed the introns. You can download the original sequences from \n", "NCBI: [HBA1](https://www.ncbi.nlm.nih.gov/nuccore/NM_000558.5), \n", "[HBA2](https://www.ncbi.nlm.nih.gov/nuccore/NM_000517.6), and \n", "[HBB](https://www.ncbi.nlm.nih.gov/nuccore/NM_000518.5).\n", "\n", "Below, the genomic sequences for a person who suffers episodes of acute \n", "generalised pain, fatigue and dactylitis are given. We suspect the patient has the sickle cell \n", "anaemia, a disease where a genetic defect leads to malformed hemoglobin (called HbS),\n", "which undergoes polymerisation and leads to typical sickle-shaped red blood cells.\n", "\n", "```\n", "alpha1globin_patient = 'TATACTGGCGCGCTCGCGGGCCGGCACTCTTCTGGTCCCCACAGACTCAGAGAGAAC\\\n", " CCACCATGGTGCTGTCTCCTGCCGACAAGACCAACGTCAAGGCCGCCTGGGGTAAGGTCGGCGCGCACGCTGGCGAG\\\n", " TATGGTGCGGAGGCCCTGGAGAGGATGTTCCTGTCCTTCCCCACCACCAAGACCTACTTCCCGCACTTCGACCTGAG\\\n", " CCACGGCTCTGCCCAGGTTAAGGGCCACGGCAAGAAGGTGGCCGACGCGCTGACCAACGCCGTGGCGCACGTGGACG\\\n", " ACATGCCCAACGCGCTGTCCGCCCTGAGCGACCTGCACGCGCACAAGCTTCGGGTGGACCCGGTCAACTTCAAGCTC\\\n", " CTAAGCCACTGCCTGCTGGTGACCCTGGCCGCCCACCTCCCCGCCGAGTTCACCCCTGCGGTGCACGCCTCCCTGGA\\\n", " CAAGTTCCTGGCTTCTGTGAGCACCGTGCTGACCTCCAAATACCGTTAAGCTGGAGCCTCGGTGGCCATGCTTCTTG\\\n", " CCCCTTGGGCCTCCCCCCAGCCCCTCCTCCCCTTCCTGCACCCGTACCCCCGTGGTCTTTGAATAAAGTCTGAGTGG\\\n", " GCGGCA'\n", "\n", "alpha2globin_patient = 'TATACTGGCGCGCTCGCGGCCCGGCACTCTTCTGGTCCCCACAGACTCAGAGAGAAC\\\n", " CCACCATGGTGCTGTCTCCTGCCGACAAGACCAACGTCAAGGCCGCCTGGGGTAAGGTCGGCGCGCACGCTGGCGAG\\\n", " TATGGTGCGGAGGCCCTGGAGAGGATGTTCCTGTCCTTCCCCACCACCAAGACCTACTTCCCGCACTTCGACCTGAG\\\n", " CCACGGCTCTGCCCAGGTTAAGGGCCACGGCAAGAAGGTGGCCGACGCGCTGACCAACGCCGTGGCGCACGTGGACG\\\n", " ACATGCCCAACGCGCTGTCCGCCCTGAGCGACCTGCACGCGCACAAGCTTCGGGTGGACCCGGTCAACTTCAAGCTC\\\n", " CTAAGCCACTGCCTGCTGGTGACCCTGGCCGCCCACCTCCCCGCCGAGTTCACCCCTGCGGTGCACGCCTCCCTGGA\\\n", " CAAGTTCCTGGCTTCTGTGAGCACCGTGCTGACCTCCAAATACCGTTAAGCTGGAGCCTCGGTAGCCGTTCCTCCTG\\\n", " CCCGCTGGGCCTCCCAACGGGCCCTCCTCCCCTCCTTGCACCGGCCCTTCCTGGTCTTTGAATAAAGTCTGAGTGGG\\\n", " CAGCA'\n", "\n", "betaglobin_patient = 'TATAGGGCAGAGCCATCTATTGCTTACATTTGCTTCTGACACAACTGTGTTCACTAGCA\\\n", " ACCTCAAACAGACACCATGGTGCATCTGACTCCTGTGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACG\\\n", " TGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTTGAGTCCTTT\\\n", " GGGGATCTGTCCACTCCTGATGCTGTTATGGGCAACCCTAAGGTGAAGGCTCATGGCAAGAAAGTGCTCGGTGCCTT\\\n", " TAGTGATGGCCTGGCTCACCTGGACAACCTCAAGGGCACCTTTGCCACACTGAGTGAGCTGCACTGTGACAAGCTGC\\\n", " ACGTGGATCCTGAGAACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTC\\\n", " ACCCCACCAGTGCAGGCTGCCTATCAGAAAGTGGTGGCTGGTGTGGCTAATGCCCTGGCCCACAAGTATCACTAAGC\\\n", " TCGCTTTCTTGCTGTCCAATTTCTATTAAAGGTTCCTTTGTTCCCTAAGTCCAACTACTAAACTGGGGGATATTATG\\\n", " AAGGGCCTTGAGCATCTGGATTCTGCCTAATAAAAAACATTTATTTTCATTGCAA'\n", "```\n", "\n", "**Exercise E**: Hemoglobin\n", "\n", "Use your function `mutationcheck()` to find out what is wrong. Try to understand\n", "how the `for` loop works and replace `A`, `B` and `C` in the code below with something \n", "else. In which subunit of hemoglobin does the mutation occur?\n", "\n", "```\n", "# Complete the following code\n", "\n", "paired_genes = [('alpha1', alpha1globin, alpha1globin_patient), \n", " ('alpha2', alpha2globin, alpha2globin_patient), \n", " ('beta', betaglobin, betaglobin_patient)]\n", "\n", "# Replace A, B and C with the correct variables:\n", "for A, B, C in paired_genes:\n", " outcome = mutationcheck(healthygene,patientgene)\n", " print(\"Mutation in \" + genename + \": \" + outcome)\n", "```\n", "\n", "Explain the outcome.\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "a8f89456", "metadata": {}, "source": [ "`````{exercise} [***] Caesar's cipher\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Joyce/15_Ceasar_cipher.py>`\n", "\n", "No doubt you will have seen the enciphering/deciphering methods with shifting the \n", "alphabet. For example, A becomes D, B becomes E, etc. This is something \n", "you can do in Python.\n", "\n", "We start with a message, written in a string. \n", "\n", "```\n", "message = 'CAESARSDECIPHERING'\n", "```\n", "\n", "Have you ever heared of ASCII (American Standard Code for \n", "Information Interchange)? Each character or string has a numerical ASCII value.\n", "For A it is 65, for Z it is 95. To convert from ASCII to a string in Python, you use the `chr()` function, whose name originates from the word 'character'.\n", "\n", "The code below generates a variable `Str`, which holds the alphabet:\n", "\n", "\n", "```\n", "alphabet = np.arange(65,91)\n", "Str = []\n", "\n", "for ii in alphabet: \n", " Str.append(chr(ii))\n", "\n", "Str=''.join(Str)\n", "print(Str)\n", "```\n", "\n", "In order to decipher our message, we need a variable `Str_decipher`, for \n", "which the variable `Str` is shifted. In this case we use a shift (Caesar \n", "number) of 2. \n", "\n", "```\n", "caesar_num = 2 # Between 0 and 25\n", "Str_decipher = Str[caesar_num:] + Str[:caesar_num]\n", "print(Str_decipher)\n", "```\n", "\n", "In order to encrypt, we need to:\n", "* go over each character in the string\n", "* find the location in the regular alphabet (`Str`), with `Str.index(character)`\n", "* find the corresponding character in the new alphabet (`Str_decipher`)\n", "* append that character to the encrypted message\n", "\n", "```\n", "new_message = []\n", "\n", "for ii in message:\n", " index = Str.index(ii) # Go over each character in the string\n", " new_character = Str_decipher[index] # Find the location in the regular alphabet\n", " new_message.append(new_character) # Extract the corresponding character in the new alphabet\n", "\n", "new_message=''.join(new_message) # Stitches all characters in the array to one string\n", "\n", "print(new_message)\n", "```\n", "\n", "**Exercise A**: Deciphering function\n", "\n", "You have seen how to encrypt. The challenge is now to decrypt a message.\n", "\n", "Let's start by making code which takes as input the Caesar number and \n", "`message_to_decipher`, and outputs the `message_original`. \n", "Name your function `Caesar_decipher`.\n", "\n", "```\n", "message = 'EGCUCTUFGEKRJGTKPI' \n", "caesar_num = 2 \n", "\n", "def Caesar_decipher(message,caesar_num):\n", " \n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise B**: Caesar number\n", "\n", "Can you decipher without the value of the Caesar number given?\n", "\n", "```\n", "message_to_decipher = 'KVCQOBFSORKWHVCIHGDOQSG'\n", "\n", "# Your code here\n", "```\n", "\n", "`````\n" ] }, { "cell_type": "markdown", "id": "03a36ed1", "metadata": {}, "source": [ "`````{exercise} [**] DNA sequence analysis\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Nina/03_DNA_analysis.py>`\n", "\n", "Write a function that takes a DNA sequence (a string of characters A, T, C, G) and returns a dictionary with the counts of each nucleotide.\n", "\n", "Handle invalid characters by ignoring them.\n", "\n", "Provide an option to return the counts as a percentage of the total number of nucleotides.\n", "\n", "Example output:\n", "\n", "```\n", "dna_count(\"ATCGATCGAATCGA\") # Returns {'A': 5, 'T': 3, 'C': 4, 'G': 3}\n", "dna_count(\"ATCGATCGAATCGA\", percent=True) # Returns {'A': 0.357, 'T': 0.214, 'C': 0.286, 'G': 0.214}\n", "```\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "468c1743", "metadata": {}, "source": [ "`````{exercise} [***] Fibonacci sequence\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Nina/01_Fibonacci.py>`\n", "\n", "Write a recursive function that generates the Fibonacci sequence up to a given number $n$ and returns a list containing the Fibonacci numbers. The Fibonacci sequence is defined as:\n", "\n", "F(0) = 0\n", "\n", "F(1) = 1\n", "\n", "F(n) = F(n-1) + F(n-2) for n > 1\n", "\n", "Example output:\n", "\n", "```\n", "fibonacci_up_to(10) # Returns [0, 1, 1, 2, 3, 5, 8]\n", "```\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "b05cfd21", "metadata": {}, "source": [ "`````{exercise} [***] Prime factorization\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Nina/02_Prime_factorization.py>`\n", "\n", "Write a function that computes the prime factorization of a given integer $n$. The function should return the prime factors in a list.\n", "Ensure that the function works for any integer greater than 1.\n", "\n", "​Example output:\n", "\n", "```\n", "prime_factors(28) # Returns [2, 2, 7]\n", "```\n", "\n", "``` \n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "84331ccc", "metadata": {}, "source": [ "`````{exercise} [***] Matrix multiplication\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_3/Nina/04_Matrix_multiplication.py>`\n", "\n", "Implement a function that multiplies two matrices. The function should handle matrices of different sizes and return the resulting matrix.\n", "\n", "Ensure the matrices can be multiplied (i.e., the number of columns in the first matrix must equal the number of rows in the second matrix).\n", "\n", "Raise an error if the multiplication cannot be performed.\n", "\n", "Note: functions for this already exist in NumPy, but try to come up with your own.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````\n" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }