{ "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", "The exercises below are intended for work in VS Code, not within the book. You can download each exercise file (`.py`) and open it in your VS Code. If the file you download from the book is `.zip`, one of the files contained within it is either a supplementary image or an answer-checker `.py` file.\n", "\n", "Each exercise carries 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": "67623dd1", "metadata": {}, "source": [ "````{exercise} [*] Numerics\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/01_Numerics.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex).\n", "\n", "**An important introduction**\n", "\n", "In Python, you can print the value of variables, which is an easy way to see whether your code was effective. You can do so using the `print()` function; put the statement or variable you want to print between the brackets. \n", "\n", "Run the following cell to print the sentence \"Hello world!\"\n", "\n", "```\n", "print(\"Hello world!\")\n", "```\n", "\n", "**Numeric types**\n", "\n", "A numeric variable, or quantitative variable, is simply a number. There are integers, which are whole numbers; floats, which are essentially decimals; and complex numbers. Note that in Python, the complex number $i$ is represented by a $j$!\n", "\n", "First, define an integer:\n", "\n", "```\n", "integer1 = # Define an integer here \n", "print(\"The type of integer1 is \", type(integer1)) # The print command allows you to see what the type is.\n", "```\n", "\n", "Now define a float:\n", "\n", "``` \n", "float1 = # Define a float here \n", "print(\"The type of float1 is \", type(float1))\n", "```\n", "\n", "Add your integer and your float together. You can do so by using the `+` operator. Check what is the type of the sum using `print()` and `type()` as in the exercise above.\n", "\n", "``` \n", "sum_integer_and_float = \n", "# Write code to print the type\n", "```\n", "\n", "As you can see from the examples above, you do not have to define the type of the variable yourself; Python will do this for you. This is very convenient, since you can simply define variables and do math without having to worry about the type.\n", "\n", "Define a complex variable:\n", "\n", "```\n", "complex1 = # Define a complex number here \n", "print(\"The type of complex1 is \", type(complex1))\n", "```\n", "\n", "Add your float and your complex number together. What happens? Why?\n", "Add your answer here.\n", "\n", "``` \n", "sum_float_and_complex = \n", "```\n", "\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "3929d068", "metadata": {}, "source": [ "````{exercise} [*] Numeric operators\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/02_Numeric_operators.py>`\n", "\n", "You can use the following [documentation](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) for this exercise.\n", "\n", "Figure out what the following operators do using the variables `a` and `b`:\n", "+ , - , *, /, %, // \n", "\n", "```\n", "a = 9\n", "b = 2\n", "\n", "# Example for +\n", "c = a + b\n", "print(c)\n", "\n", "# Your code here\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "b6c80cb1", "metadata": {}, "source": [ "````{exercise} [*] Numerics type conversion\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/03_Numeric_type_conversion.py>`\n", "\n", "For more information on this exercise, you can use [this link](https://www.datacamp.com/tutorial/python-data-type-conversion).\n", "\n", "Python infers the type of the variable based on context. In this exercise, we will explore three ways in which you can change the type of a variable by coding it in a specific way. We will do so by changing an integer into a float.\n", "\n", "```\n", "initial_integer = 5\n", "print(type(initial_integer))\n", "```\n", "\n", "**Redefining a variable**\n", "\n", "When you redefine a variable (using `=`), Python immediately changes the type of the variable to match the definition. Redefine the variable `initial_integer` to make it a float (hint: remember the definition of a float?). \n", "\n", "```\n", "initial_integer = # Put your code here\n", "print(type(initial_integer))\n", "```\n", "\n", "As you can see, as we redefined the variable into one containing a decimal point, Python now recognizes it as a float. For the next exercise, we need to go back to our initial integer; we do so by running the following code.\n", "\n", "```\n", "initial_integer = 5\n", "print(type(initial_integer))\n", "```\n", "\n", "**Using Python's built-in function**\n", "\n", "To make a variable of a specific type, we can use Python's built-in type converters. To change a variable into a float, we use `float()`. To change it into an integer, we use `int()`. Convert the variable `initial_integer` to a float using the built-in converter.\n", "\n", "```\n", "initial_integer = # Put your code here\n", "print(type(initial_integer))\n", "```\n", "\n", "Note that this will only work if Python can reasonably recognize the type you're converting to in the variable. For example, when we try to covert a complex number into a float, we run into a problem:\n", "\n", "```\n", "complex_number = 5 + 1j\n", "converted = float(complex_number)\n", "```\n", "\n", "For the next exercise, we again have to redefine the original integer so we can explore the last method to convert it into a float. Run the following code:\n", "\n", "```\n", "initial_integer = 5\n", "print(type(initial_integer))\n", "```\n", "\n", "**Using calculations**\n", "\n", "As you perform calculations, Python will infer the new type based on the operations that you use. This is of course very useful, as there are many examples of going from an integer to a float by performing certain operations. \n", "\n", "Convert the variable `initial_integer` to a float by using numeric operators.\n", "\n", "```\n", "initial_integer = # Put your code here\n", "print(type(initial_integer))\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "4a1fb83b", "metadata": {}, "source": [ "````{exercise} [*] Boolean variables\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/04_Boolean.py>`\n", "\n", "\n", "A Boolean variable can take two values: `True` or `False`. You can use it for applying logic in Python, which you will encounter later in the book. As you saw in the last exercise, you can convert variables to another type. By converting a variable to a Boolean object, you can check the \"truth value\" that Python assigns to the variable. \n", "\n", "Check the truth value of the following variable values by using `bool()` and `print()`.\n", "\n", "```\n", "a = 10\n", "b = 3.4\n", "c = 2 + 3j\n", "d = 0\n", "\n", "# Write your code here.\n", "```\n", "\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "520ae2ed", "metadata": {}, "source": [ "````{exercise} [*] Strings\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/05_Strings.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str).\n", "\n", "A *sequence* is a data structure that contains items arranged in order, and you can access each item using an integer index that represents its position in the sequence. Note that Python starts counting at zero!\n", "\n", "A *string* is a sequence of characters. It is useful for representing text. We make a string by using single or double quotation marks.\n", "\n", "In this exercise, we will explore a strand of genetic material. First, check the data type of the following strand:\n", "\n", "```\n", "strand = \"ACGUGCAGCUCGGGCGAUCGCGCUAAAGCGCAUUCGCGUACGAUGGGCGAA\"\n", "# Your code here\n", "```\n", "\n", "As genetic material is often represented by letters, we use strings to encode them. There are a few operations you can perform on strings that make them easy to inspect and manipulate. \n", "\n", "As you can see from the strand above, it must be an RNA strand due to the presence of uracil. However, you may have a very long string of characters and not be able to see immediately whether there are U-bases in the strand. Write a piece of code that uses a Boolean variable to check whether there are U bases in a strand.\n", "\n", "```\n", "contains_U_bases = .. in .. \n", "# Here, \"in\" is used to make Python search for a specific character in a string. If found, it returns \"True\".\n", "\n", "print(type(contains_U_bases))\n", "print(f\"This strand contains U-bases and is therefore an RNA strand: {contains_U_bases}\")\n", "```\n", "\n", "Now, turn this RNA strand into an mRNA strand by adding a G-cap and a poly-A-tail. Note that you can add strings together using the `+` operator.\n", "\n", "```\n", "G_cap =\n", "poly_A_tail =\n", "mRNA_strand =\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "cfefb07f", "metadata": {}, "source": [ "````{exercise} [*] Print statement\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/06_Print_statements.py>`\n", "\n", "You can use the following [documentation](https://docs.python.org/3/library/functions.html#print) for this exercise.\n", "\n", "You have already encountered some examples of the `print()` function. The print function allows you to read the outputs of your code. It is a versatile tool that is very useful for debugging and figuring out whether your code actually does what you think it does. In this exercise, we will explore some useful properties of the print function.\n", "\n", "The print function itself is fairly simple. Use it to print the statement \"The answer is 42\". \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "You can also use `print()` to print the value of a variable. Define and print a variable in the following cell.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "You can do some simple formatting in a print statement. For example, use `\\n` for an enter and `\\t`for a tab. Print this haiku in the proper form (5/7/5 syllables per line): \"coding is the best / don’t let it make you feel dumb / keep calm, debug on\".\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "Finally, you can enter multiple variables and/or objects in a single print statement using commas to separate the string and the variables. In the following code, print a cohesive sentence containing all information on the following protein:\n", "\n", "```\n", "protein_name = \"Sonic Hedgehog protein\"\n", "number_of_amino_acids = 462\n", "location_encoding_gene = \"Chromosome 7\"\n", "\n", "# Your code here\n", "```\n", "\n", "**Formatted strings (f-strings)**\n", "\n", "To combine multiple types of variables in a string or in a print statement, we can also use f-strings. These usually make your code a bit more readable. To create an f-string, we preface the string with an f (`f\"..\"`) and we put the variables between curly brackets (`{variable}`). For example:\n", "\n", "```\n", "print(f\"The {protein_name} has {number_of_amino_acids} amino acids and can be found on {location_encoding_gene}.\")\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "95b9dc94", "metadata": {}, "source": [ "````{exercise} [*] Input\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/07_Input.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/library/functions.html#input).\n", "\n", "The `input()` function allows you pass information to Python. Between the brackets, you can specify the prompt that Python shows you when you have to enter something.\n", "\n", "Run the following code and provide the input that is asked for. Check the type of the input you provided.\n", "\n", "```\n", "a = input(\"Input a string. \")\n", "b = input(\"Input an integer. \")\n", "c = input(\"Input a float. \")\n", "\n", "# write code to check the types here\n", "```\n", "\n", "As you can see above, Python always interprets your response as a string. To use the variable further, you need to convert it to the type you want. In the code below, use `input()` and type converting functions to get the variable type that you want. Verify that it worked using `print` statements.\n", "\n", "```\n", "b =\n", "c =\n", "```\n", "\n", "You can also directly input multiple variables. In this example, we will input one integer and one float separated by space and save it as `two_numbers` string. To then separate the two inputs, we use a comma before the equal sign (`b,c =`) and the built-in function `.split()` which cuts up the string (as default, based on spaces). It can be used as follows: `string_name.split()`, so in our case `b,c = two_numbers.split()`.\n", "\n", "```\n", "two_numbers = input(\"Input an integer and a float separated by a space\")\n", "b,c = two_numbers.split()\n", "print(f\"The first variable is {b} and the second variable is {c}.\")\n", "```\n", "\n", "Now write the code to do the same using two lines: one line to ask for input and split the string, and the other a print line.\n", "\n", "```\n", "# your code here\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "e06748de", "metadata": {}, "source": [ "````{exercise} [*] Sequences\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/08_Sequences.zip>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/library/stdtypes.html#string-methods).\n", "\n", "**Tuples**\n", "\n", "A *sequence* is a data structure that contains items arranged in order, and you can access each item using an integer index that represents its position in the sequence. You have already encountered strings as an example of a sequence.\n", "\n", "A *tuple* can be used to store multiple items in a single variable. Tuples are immutable, meaning that they cannot be changed after they have been defined. They are indicated by round brackets: `(item1, item2, ..)`.\n", "\n", "In this exercise, we consider a DNA sequence, which is stored as strings. Determine the GC-content of the sequence; this is the fraction of the DNA sequence made up by G or C bases. The GC-content is important to determine the stability of the DNA-molecule. We use the method `.count()` to find how many occurrences there are of a specific base in a string.\n", "\n", "```\n", "DNA_sequence = \"GTACGAGCATGCTGG\"\n", "G_number = DNA_sequence.count(\"G\")\n", "# Extend the code for other bases\n", "```\n", "\n", "Knowing the number of G and C bases, we can determine the melting temperature of the DNA, i.e., the temperature at which the strands separate from one another, using the Wallace rule:\n", "\n", "$ T_m \\text{ (in }^{\\circ}C\\text{)} = 4 * \\text{(number of Gs + number of Cs)}+ 2 * \\text{(number of As + number of Ts)}$\n", "\n", "Calculate the melting temperature of the DNA sequence.\n", "\n", "```\n", "melting_temperature = # add your code here\n", "print(f\"The melting temperature is {melting_temperature} degrees Celsius\")\n", "```\n", "\n", "Store the variables with information on the DNA (melting temperature, GC content) in a tuple to have all of it in one place:\n", "\n", "```\n", "sequence_information = (.., ..)\n", "```\n", "\n", "Run the following code to check whether your `sequence_information` is correct:\n", "\n", "```\n", "from check_08 import *\n", "check_08(DNA_sequence, sequence_information)\n", "```\n", "\n", "Imagine we want to raise the melting temperature and increase the stability. To do so, we would have to increase the GC-content. Add 4 G or C bases to the original string and calculate the new melting temperature.\n", "\n", "```\n", "new_DNA_sequence =\n", "new_melting_temperature =\n", "```\n", "\n", "Index the tuple `sequence_information` to retrieve the `melting_temperature` of the initial strand. By how much did the melting temperature increase?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "7ff0d34b", "metadata": {}, "source": [ "````{exercise} [*] Lists\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/09_Lists.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists).\n", "\n", "A *sequence* is a data structure that contains items arranged in order, and you can access each item using an integer index that represents its position in the sequence. You have already encountered strings as an example of a sequence.\n", "\n", "*Lists* allow you to store multiple items in a single variable. They have a defined order, which allows you to retrieve items based on their position in the list. Contrary to tuples, however, lists are mutable, which means you can easy change, add, or remove items.\n", "\n", "In this exercise, we'll explore the usefulness of lists by looking at a list containing all 20 naturally occurring amino acids:\n", "\n", "```\n", "amino_acids = [\n", " \"Methionine\", \"Histidine\", \"Threonine\", \"Arginine\", \"Alanine\",\n", " \"Glycine\", \"Tyrosine\", \"Proline\", \"Asparagine\", \"Valine\",\n", " \"Phenylalanine\", \"Leucine\", \"Glutamine\", \"Cysteine\", \"Aspartic acid\",\n", " \"Isoleucine\", \"Serine\", \"Tryptophan\", \"Lysine\", \"Glutamic acid\"\n", "]\n", "```\n", "\n", "First, sort this list alphabetically using built-in function `sorted()`.\n", "\n", "```\n", "amino_acids = # Add your code here\n", "```\n", "\n", "Now, determine the index of Glutamine (hint: see the documentation) and use that to retrieve it from the list:\n", "\n", "```\n", "index_glutamine =\n", "glutamine = amino_acids[..]\n", "print(glutamine)\n", "```\n", "\n", "Define a list of all amino acids starting with an A by using slicing, i.e., indexing of multiple items. You can slice multiple items as follows: `list_name[start:stop]` - the item with index start will be included, whereas the item with index stop *will not* be included.\n", "\n", "```\n", "amino_acids_starting_with_an_A =\n", "print(amino_acids_starting_with_an_A)\n", "```\n", "\n", "Add the amino acid \"Selenocysteine\", the Se-analogue of cysteine, to the list. Make sure that your final list is again sorted alphabetically!\n", "\n", "```\n", "# Add your code here\n", "```\n", "\n", "You can check whether a specific item is in a list using a Boolean variable. Use `input()` and the Boolean variable `is_this_an_amino_acid` to check whether your input string is in the extended list of amino acids.\n", "\n", "```\n", "your_amino_acid = input() # make sure that this variable is of the correct type\n", "is_this_an_amino_acid = .. in ..\n", "print(f\"{your_amino_acid} is an amino acid: {is_this_an_amino_acid}\")\n", "```\n", "\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "c4eba320", "metadata": {}, "source": [ "````{exercise} [*] Dictionaries\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/10_Dictionaries.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/tutorial/datastructures.html#dictionaries).\n", "\n", "A dictionary is associative: it links a category to its components, or in Python-language, a key to its values. You can change a dictionary after it has been defined, i.e., it is mutable or changeable.\n", "\n", "Make a dictionary which contains the words of a sentence as keys and the next word as value. For example, the sentence \"Luke, I am your father\" would correspond to the following dictionary:\n", "\n", "```\n", "example_sentence_dictionary = {\"Luke\" : \"I\", \n", " \"I\" : \"am\", \n", " \"am\" : \"your\", \n", " \"your\" : \"father\"}\n", "```\n", "\n", "Make a similar dictionary for the sentence: \"if you can do it\". Do so by defining an empty dictionary and progressively adding items.\n", "\n", "```\n", "sentence_dictionary = {} # Define an empty dictionary\n", "\n", "# You can add an item to the dictionary in the following way:\n", "sentence_dictionary[\"if\"] = \"you\"\n", "```\n", "\n", "Now if we slightly change our sentence, we want to be able to remove a key and its value. The new sentence is: \"you can do it\".\n", "\n", "Change the existing dictionary to reflect the change in the sentence. Use the `.pop()` method to remove an item. Between the brackets, you only have the include the key; `.pop()` will then remove both the key and its value.\n", "\n", "```\n", "# Add your code here\n", "\n", "print(sentence_dictionary)\n", "```\n", "\n", "Now imagine you want to see which word comes after \"do\" in the sentence. You can retrieve a value corresponding to a specific key by \"indexing\" the dictionary with that key. Try this yourself to see which word comes after \"can\". Also check what happens when you enter a key that is not in the dictionary at all; what kind of error do you get?\n", "\n", "```\n", "word_after = sentence_dictionary[\"do\"]\n", "print(word_after)\n", "```\n", "\n", "Making a sentence dictionary becomes more difficult if you have words that appear in the sentence multiple times. As a value can only contain one variable, you will need to use a list to have multiple words associated to one key. For example, the sentence \"It's the eye of the tiger\" would become\n", "\n", "```\n", "sentence_dictionary = {\"It's\" : [\"the\"], \n", " \"the\" : [\"eye\", \"tiger\"], \n", " \"eye\" : [\"of\"], \n", " \"of\" : [\"the\"]}\n", "```\n", "\n", "Make such a dictionary yourself of the sentence \"I drink coffee and I eat a pastry\". Again, start from an empty dictionary and progressively add items. Remember: if you want to add an item to a list, you can use the method `.append()`.\n", "\n", "```\n", "sentence_dictionary = {}\n", "sentence_dictionary[\"I\"] = [\"drink\"]\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "8d4dc8ea", "metadata": {}, "source": [ "````{exercise} [**] Sets\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/11_Sets.py>`\n", "\n", "For this exercise, you can use the following [documentation](https://docs.python.org/3/tutorial/datastructures.html#sets).\n", "\n", "A set is a variable that, like a tuple, is immutable. Furthermore, it is not ordered (so you cannot retrieve items based on their index), and there cannot be any duplicates in a set. \n", "\n", "In this exercise, we will explore some of the applications of sets. First consider the following list with all individual types of cells found in a (very small) patient sample of a tumour.\n", "\n", "```\n", "tumor_cells = ['T cell', 'Dendritic cell', 'T cell', 'Dendritic cell', 'Cancer cell', 'B cell',\n", " 'Macrophage', 'Cancer cell', 'Cancer cell', 'Macrophage', 'B cell', 'Fibroblast', 'T cell',\n", " 'T cell', 'Cancer cell', 'Macrophage', 'Dendritic cell', 'Tumor-infiltrating lymphocyte',\n", " 'Tumor-infiltrating lymphocyte', 'Macrophage', 'Cancer cell', 'Endothelial cell',\n", " 'Cancer cell', 'Fibroblast', 'Dendritic cell', 'Endothelial cell',\n", " 'B cell', 'Cancer cell', 'Tumor-infiltrating lymphocyte', 'Fibroblast', 'T cell',\n", " 'Endothelial cell', 'T cell', 'Macrophage', 'Endothelial cell', 'Macrophage', 'B cell', 'Cancer cell',\n", " 'Cancer cell', 'T cell', 'Cancer cell']\n", "```\n", "\n", "First check how many items there are in this list by using the built-in function `len()`.\n", "\n", "```\n", "number_of_cells = # Put your code here\n", "```\n", "\n", "Then, check how many cancer cells there are in the sample using `count()`, and what percentage of all cells is made up by cancer cells.\n", "\n", "``` \n", "# Your code here\n", "```\n", "\n", "Now, to get a better overview of the cells that are actually present, we would like to remove all duplicates. The easiest way to do this is by turning the list into a set using `set()`. Print the result.\n", "\n", "```\n", "unique_cell_types = set(tumor_cells)\n", "```\n", "\n", "From this list of cell types, we see three categories: immune cells (T cell, B cell, Macrophage, Tumor-infiltrating lymphocyte, Dendritic cell), stromal cells (Endothelial cell, Fibroblast) and cancer cells. Create a dictionary with the category as key and a list of the corresponding cell types as value.\n", "\n", "```\n", "categories_of_cells =\n", "```\n", "\n", "You receive a second sample of cells. You want to figure out whether there are any types that are in the first sample (from now on referred to as sample A) but not in the second sample (sample B). Fortunately, you can apply set theory in Python on sets, meaning that you can find their difference (using `-`), but also their intersection (using `&`), their union (using `|`), their difference (using `^`) and more. \n", "\n", "Find the cell types that differ between sample A and sample B.\n", "\n", "```\n", "tumor_cells_sample_B = ['Neutrophil', 'Dendritic cell', 'T cell', 'Dendritic cell', 'Cancer cell', 'Neutrophil', 'Pericytes', 'Cancer cell', \n", " 'Cancer cell', 'Pericytes', 'Neutrophil', 'Fibroblast', 'T cell', 'T cell', 'Cancer cell', 'Pericytes', 'Dendritic cell', \n", " 'Tumor-infiltrating lymphocyte', 'Tumor-infiltrating lymphocyte', 'Pericytes', 'Neutrophil', 'Endothelial cell', \n", " 'Cancer cell', 'Fibroblast', 'Dendritic cell', 'Neutrophil', 'B cell', 'Cancer cell', 'Tumor-infiltrating lymphocyte', \n", " 'Fibroblast', 'Neutrophil', 'Endothelial cell', 'T cell', 'Pericytes', 'Endothelial cell', 'Pericytes', 'B cell', \n", " 'Cancer cell', 'Cancer cell', 'T cell', 'Neutrophil']\n", "\n", "# Your code here\n", "```\n", "\n", "Finally, going back to our set of unique cell types in sample A, we note that we're not terribly interested in the stromal cells (i.e., the fibroblasts and the endothelial cells). Remove these from the cell types.\n", "\n", "HINT: remember, sets are immutable! To change the items in this variable, you'll have to change it back to something that is mutable.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "85ea1bd7", "metadata": {}, "source": [ "````{exercise} [**] Organelles\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/12_Organelles.py>`\n", "\n", "You receive the radius of a typical human skin cell, as well as two dictionaries, one with the radii of various organelles and one with the number of these organelles typically found in a skin cell. Write a piece of code that calculates the volume percentage each of these organelles takes up in the cell. You may assume that the organelles are spherical.\n", "\n", "Store the volume percentages in a dictionary named `volume_percentages` with the same keys as the original two dictionaries. Do not round the percentages.\n", "\n", "```\n", "pi = 3.1415\n", "\n", "cell_radius = 40 # micrometers\n", "\n", "organelle_radius = {\"nucleus\" : 15,\n", " \"mitochondrion\" : 3,\n", " \"golgi\" : 5e-1,\n", " \"ribosome\" : 1e-3} # all in micrometers\n", "\n", "organelle_number = {\"nucleus\" : 1,\n", " \"mitochondrion\" : 200,\n", " \"golgi\" : 1,\n", " \"ribosome\" : 10e7}\n", "\n", "# Start your solution here\n", "```\n", "\n", "```{admonition} Solution to this exercise\n", ":class: note, dropdown\n", "{'nucleus': 5.2734375, 'mitochondrion': 8.437500000000002, 'golgi': 0.0001953125, 'ribosome': 0.00015625}\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "96005bc6", "metadata": {}, "source": [ "````{exercise} [**] Mutating a genome\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/13_Mutating_a_genome.py>`\n", "\n", "An organism with a very small genome has 3 chromosome pairs of 6, 8, and 10 bases. You get a list of these chromosomes in order (i.e., the first two entries are your chromosome 1 set, the second two entries are the chromosome 2 set, etc.). You want to mutate chromosome 3 such that the 7th base becomes a \"G\" in both copies. Use square brackets to access chromosomes and nucleotide bases.\n", "\n", "```\n", "genome = [\"CGTACG\", \"GTCTAT\", \n", " \"ATTCTACA\", \"TGCAAGCT\",\n", " \"TGCGCACTAC\", \"ATGCTATCTG\"]\n", " \n", "# Start your solution here\n", "\n", "```\n", "\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "9433be64", "metadata": {}, "source": [ "````{exercise} [*] Watermelons (error types I)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/14_Watermelons.py>`\n", "\n", "The code below will give an error. Figure out what the type and the source of the error is and fix it.\n", "\n", "```\n", "price_watermelon_per_kilo = 1.97 # euros\n", "number_of_small_watermelons = 20\n", "number_of_big_watermelons = 15\n", "weight_small_watermelon = 2.7 # kilograms\n", "weight_big_watermelon = 4 # kilograms\n", "\n", "total = price_watermelon_per_kilo * (number_of_small_watermelons * weight_small_watermelon +\n", " number_of_big_watermelons * weight_big_watermelon)\n", "\n", "total = round(total, 2)\n", "\n", "print(\"The total price is €\" + total)\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "5f674720", "metadata": {}, "source": [ "````{exercise} [*] RNA to mRNA (error types II)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/15_RNA_to_mRNA.py>`\n", "\n", "This code checks the length of an RNA strand and the maximum potential length of its corresponding protein. Next, it turns the RNA strand into an mRNA strand and checks whether this was successful.\n", "\n", "The code below will give an error. Figure out the type and the source of the error and fix it.\n", "\n", "```\n", "RNA_strand = \"ACGACCGGGAAGCACGGACCGGAAGGCGCGACCAAGGCGCACGGGACGUGAACGCCGACGGGACCGGCGACGAC\"\n", "\n", "# Determination of characteristics\n", "length_of_RNA_strand = len(RNA_strand)\n", "mod_RNA_bases = lenght_of_RNA_strand % 3 # Here, we calculate how many bases are not part of a triplet\n", "maximum_potential_length_protein = (length_of_RNA_strand - mod_RNA_bases) / 3\n", "print(f\"The maximum potential length of the protein is {maximum_potential_length_protein:.0f} amino acids.\")\n", "\n", "# Transformation into mRNA\n", "G_cap = \"G\"\n", "poly_A_tail = \"AAAAAAAAAAAAAAAA\"\n", "mRNA_strand = G_cap + RNA_strand + poly_A_tail\n", "\n", "successfully_G_capped = (mRNA_strand[0] == \"G\") # Looks at the first character in the string\n", "successfully_A_tailed = (mRNA_strand[-5:-1] == \"AAAA\") # Looks at the final four characters\n", "\n", "print(f\"The RNA strand has been successfully transformed into mRNA: {successfully_A_tailed and successfully_G_capped}\")\n", "# The word \"and\" only returns True if both conditions are True.\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "bff0ac17", "metadata": {}, "source": [ "````{exercise} [**] Measurements (error types III)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/16_Measurements.py>`\n", "\n", "We want to take a list of ten measurements and calculate the average and range.\n", "\n", "The code contains two mistakes. One of these will give an error, the other is a conceptual mistake. Figure out the mistakes and fix them; furthermore, figure out what type of error this code gives.\n", "\n", "```\n", "measurements = [1.5, 3.0, 2.7, 1.1, 7.8, 5.4, 3.7, 4.4, 9.6, 5.6]\n", "measurements = sorted(measurements)\n", "\n", "print(f\"The sorted list of measurements is the following: {measurements}\")\n", "\n", "number_of_measurements = len(measurements)\n", "\n", "highest_value = measurements[number_of_measurements] \n", "lowest_value = measurements[1] \n", "range = highest_value - lowest_value\n", "average = sum(measurements) / number_of_measurements\n", "\n", "print(f\"The range of the measurements is {range:.2} whereas the average of the measurements is {average:.2}.\")\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "b12c5a55", "metadata": {}, "source": [ "````{exercise} [**] Air bubble velocity\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Margreet/01_Air_bubble_velocity.py>`\n", "\n", "Air bubbles \"trapped\" in a viscous liquid will slowly rise to the surface. The velocity of these bubbles can be calculated by solving the force balance equation: \n", "\n", "$$k \\cdot v = (\\rho_V-\\rho_w)\\cdot V \\cdot g$$\n", "\n", "where $k$ is a drag coefficient, $v$ the velocity of the bubble, $\\rho_V$ the density of the air bubble, $\\rho_w$ the density of the liquid, $V$ the volume of the bubble (assumed to be spherical), and $g$ the acceleration due to gravity. All numbers should be given using standard SI units (kg, m, s, etc.). \n", "\n", "The outline code to calculate the air bubble velocity is given below. \n", "\n", "Your task is to:\n", "* Complete the code, where the diameter is asked as input value by the user in cm. \n", "* Calculate the volume of the spherical air bubble. Use 3.14 as the value of $\\pi$.\n", "* Print the velocity of the air bubble and the associated unit, e.g., \"The velocity is: .... m/s.\".\n", "* It is considered good practice that the units are given directly after the numbers (as shown with $g$). Provide the three missing units in the code below. \n", "\n", "```\n", "k = 0.25 # Add unit\n", "rho_V = 1.29 # Add unit\n", "rho_w = 0.998 # Add unit\n", "g = 9.81 # m/s^2\n", "\n", "# Your code for defining d and V\n", "\n", "# Your code for calculating the air bubble velocity and printing output\n", "\n", "```\n", "````" ] }, { "cell_type": "markdown", "id": "5cf1b938", "metadata": {}, "source": [ "````{exercise} [**] Bacterial growth (error types IV)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/17_Bacterial_growth.py>`\n", "\n", "Imagine you are in the lab growing bacterial colonies. As bacteria are allowed to divide, they will accumulate DNA damage. This code calculates the average number of mutations that have occurred in a bacterium over a specific amount of time.\n", "\n", "The code contains two mistakes. Both these mistakes will give an error. Figure out what these errors mean and fix the mistakes in the code.\n", "\n", "```\n", "mutation_rate = 1e-10 # This means that for every 10 billion bases copied, there will be one mutation\n", "genome_size = 4e6 # This is approximate, since it - technically speaking - depends on the species\n", "initial_number_of_bacteria = 1e3\n", "\n", "# The generation time is the time a specific species needs to divide, i.e. double its population.\n", "generation_time_various_bacteria = {\"C. perfringens\" : 10\n", " \"E. coli\" : 20\n", " \"S. enterica\" : 30\n", " \"P. aeruginosa\" : 30\n", " \"V. cholerae\" : 40}\n", "\n", "bacterial_species = input(\"What are bacterial species are you working with? \")\n", "time_elapsed = int(input(\"For how many minutes have the bacteria been allowed to divide?\"))\n", "\n", "# The following two lines of code checks whether the growth of bacteria has plateaued by setting an upper limit to the division time. \n", "time_elapsed = max(time_elapsed, 1000)\n", "\n", "generation_time = generation_time_various_bacteria[\"bacterial_species\"] # We take the generation time of the entered species\n", "number_of_divisions = round(time_elapsed/generation_time) # We calculate how many divisions have taken place in the specified time\n", "total_number_of_bacteria = initial_number_of_bacteria * 2**number_of_divisions # We find the total number of bacteria after these divisions\n", "number_of_mutations_per_bacterium = number_of_divisions * genome_size * mutation_rate # We find the number of mutations so far\n", "\n", "print(f\"On average, the number of mutations per bacterium is {number_of_mutations_per_bacterium:.2}, \"\n", " f\"there will be one mutation in every {(1/number_of_mutations_per_bacterium):.2f} bacteria.\")\n", "\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "0356e370", "metadata": {}, "source": [ "````{exercise} [***] Atomic force microscopy (AFM) data\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/18_AFM.zip>`\n", "\n", "You are studying a protein in different conformations under the AFM. Your raw data is a list of numbers; every number corresponds to a specific conformation. You also receive an image (see below) containing the names of the conformations that the numbers correspond to. Convert the list of numbers to a dictionary which has the names of the conformations as key and the number of times that this conformation has been found as value. \n", "\n", "```{figure} ../Coding_exercises/Week_1/Lisa/18\\ -\\ AFM\\ data/SMC\\ conformations.png\n", "---\n", "height: 150px\n", "name: afm\n", "---\n", "```\n", "\n", "```\n", "conformations = [2, 1, 3, 2, 1, 3, 2, 2, 1, 1, 3, 3, 1, 2, 2, 1, 3, 1, 1, 2, 3, 3, 2, 1, 2, 2, 3, 1, 1, 3, 3, 2, 1, 2, 1, 1, 3, 3, 2, 2, 1, 3, 1, 2, 2, 3, 3, 1, 2, 1, 1, 3, 3, 2, 1, 1, 2, 3, 3, 1, 2, 2, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 3, 3, 1, 1, 2, 2, 1, 3, 3, 1, 2, 2, 3, 1, 1, 3, 2, 2, 1, 1, 3, 2, 2, 1, 1, 3, 2, 1, 3, 1, 1, 2, 3, 2, 1, 1, 3, 3, 2, 1, 2, 1, 3, 3, 2, 1, 1, 3, 2, 2, 1, 3, 3, 1, 2, 1, 1, 3, 2, 1, 3, 1, 2, 2, 3, 1, 1, 3, 2, 2, 1, 1, 3, 3, 1, 2, 1, 3, 2]\n", "\n", "# Your code here\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "d5617bf1", "metadata": {}, "source": [ "````{exercise} [***] Different clock\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/19_Different_clock.zip>`\n", "\n", "We have 24 hours per day, 60 minutes per day, and 60 seconds per minute. A new clock is proposed: 10 tiks per day, 100 taks per tik, and 100 toks per tak. Write a function to convert our regular 24:60:60 time to tik-tak-tok's 10:100:100 time.\n", "\n", "First, calculate how many seconds there are in a day:\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "Now calculate how many seconds one 'tak' is:\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "Use this information to reprogram a digital clock from the max 23:59:59 in hours:min:seconds, to max 09:99:99 in tik:tak:tok. \n", "\n", "```\n", "hms = [15, 26, 39]\n", "\n", "# put your code here\n", "\n", "tik_tak_tok = \n", "```\n", "\n", "Run the following code to check whether your solution is correct:\n", "\n", "```\n", "from check_19 import *\n", "check_19(hms, tik_tak_tok)\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "id": "ecc37557", "metadata": {}, "source": [ "````{exercise} [***] Inverting a codon dictionary\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_1/Lisa/20_Inverting_a_codon_dictionary.py>`\n", "\n", "Below, you'll find a dictionary showing which codons (only the ones starting with an A for simplicity purposes) correspond to which amino acid. In this dictionary, the amino acid is the key of each entry, whereas the corresponding codons are the items.\n", "\n", "In the exercise, you must invert this dictionary, such that the keys are the items and the items are amino acids. Note that you need loops for this exercise, which will only be covered later in the book, so we recommend only trying this exercise if you have some previous programming experience.\n", "\n", "```\n", "amino_acid_to_codon_A = {\n", " 'Lysine': ['AAA', 'AAG'],\n", " 'Asparagine': ['AAC', 'AAU'],\n", " 'Threonine': ['ACA', 'ACC', 'ACG', 'ACU'],\n", " 'Arginine': ['AGA', 'AGG'],\n", " 'Serine': ['AGC', 'AGU'],\n", " 'Isoleucine': ['AUA', 'AUC', 'AUU'],\n", " 'Methionine': ['AUG']\n", "}\n", "\n", "codon_to_amino_acid_A = {}\n", "\n", "for amino_acid, codons in amino_acid_to_codon_A.items():\n", "# Your code here\n", "```\n", " \n", "````" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }