Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save francois-durand/d7f814a4336d3d00d3adec4cdf75113b to your computer and use it in GitHub Desktop.
Save francois-durand/d7f814a4336d3d00d3adec4cdf75113b to your computer and use it in GitHub Desktop.
a_bit_of_gymnastics_in_python_with_solutions.ipynb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {},
"id": "cc5e76ab",
"cell_type": "markdown",
"source": "# A Bit of Gymnastics in Python (Problems + Solutions)"
},
{
"metadata": {},
"id": "5c4c70bb",
"cell_type": "markdown",
"source": "In this interactive session, I will propose exercises inspired by the most popular questions about Python in Stack Overflow: https://stackoverflow.com/questions/tagged/python?tab=votes.\n\nHere is the approach of the session:\n\n* For beginners, search answers on the web, discover some elements of the Python syntax;\n* For more advanced users, try to do as much as possible without any help from the web, gain speed and agility, find several answers to the same question.\n\nRequirements: a computer with a Python installation + Jupyter Notebook. Only a minimal knowledge of Python is necessary."
},
{
"metadata": {},
"id": "0230edac",
"cell_type": "markdown",
"source": "## Ternary operator"
},
{
"metadata": {},
"id": "fb7a1bb4",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.159225Z",
"end_time": "2023-04-19T11:33:51.174226Z"
},
"trusted": true
},
"id": "afcdfd0a",
"cell_type": "code",
"source": "def foo():\n print('Long computation of foo()...')\n return 'foo'",
"execution_count": 1,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.175228Z",
"end_time": "2023-04-19T11:33:51.190226Z"
},
"trusted": true
},
"id": "6564eaaf",
"cell_type": "code",
"source": "def bar():\n print('Long computation of bar()...')\n return 'bar'",
"execution_count": 2,
"outputs": []
},
{
"metadata": {},
"id": "858733ea",
"cell_type": "markdown",
"source": "Implement the following function:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.191238Z",
"end_time": "2023-04-19T11:33:51.206233Z"
},
"trusted": true
},
"id": "c7c5e29e",
"cell_type": "code",
"source": "def h(x):\n \"\"\"If x, then foo(), else bar().\n \n Evaluation is lazy: for example, if x is True, then only foo() is computed, not bar().\n \n Parameters\n ----------\n x: bool\n \n Returns\n -------\n str\n If x, then foo(), else bar().\n \n Examples\n --------\n >>> h(True)\n Long computation of foo()...\n 'foo'\n\n >>> h(False)\n Long computation of bar()...\n 'bar'\n \"\"\"\n pass",
"execution_count": 3,
"outputs": []
},
{
"metadata": {},
"id": "330d5cf4",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.207226Z",
"end_time": "2023-04-19T11:33:51.222226Z"
},
"trusted": true
},
"id": "5c1d6db8",
"cell_type": "code",
"source": "def h(x):\n return foo() if x else bar()",
"execution_count": 4,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.223226Z",
"end_time": "2023-04-19T11:33:51.237237Z"
},
"trusted": true
},
"id": "617c0a86",
"cell_type": "code",
"source": "h(True)",
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"text": "Long computation of foo()...\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"execution_count": 5,
"data": {
"text/plain": "'foo'"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.238240Z",
"end_time": "2023-04-19T11:33:51.252183Z"
},
"trusted": true
},
"id": "493654ec",
"cell_type": "code",
"source": "h(False)",
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"text": "Long computation of bar()...\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"execution_count": 6,
"data": {
"text/plain": "'bar'"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.253204Z",
"end_time": "2023-04-19T11:33:51.267690Z"
},
"trusted": true
},
"id": "f6d74144",
"cell_type": "code",
"source": "def h(x):\n if x:\n return foo()\n return bar()",
"execution_count": 7,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.269733Z",
"end_time": "2023-04-19T11:33:51.282814Z"
},
"trusted": true
},
"id": "0bb6a01a",
"cell_type": "code",
"source": "h(True)",
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"text": "Long computation of foo()...\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"execution_count": 8,
"data": {
"text/plain": "'foo'"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.284818Z",
"end_time": "2023-04-19T11:33:51.298560Z"
},
"trusted": true
},
"id": "7f0dedde",
"cell_type": "code",
"source": "h(False)",
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"text": "Long computation of bar()...\n",
"name": "stdout"
},
{
"output_type": "execute_result",
"execution_count": 9,
"data": {
"text/plain": "'bar'"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "3841f32e",
"cell_type": "markdown",
"source": "## Check whether a file exists when opening it"
},
{
"metadata": {},
"id": "8f4d5cd5",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {},
"id": "11e8fed8",
"cell_type": "markdown",
"source": "Implement the following function:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.299549Z",
"end_time": "2023-04-19T11:33:51.314676Z"
},
"trusted": true
},
"id": "9f260a4b",
"cell_type": "code",
"source": "def read_file(file_name):\n \"\"\"Read a file if it exists.\n \n Print each line of the file. If the file does not exist, print 'File not found'.\n \n Parameters\n ----------\n file_name: str\n Name of the file.\n \n Examples\n --------\n >>> read_file('existing_file.txt')\n This is the first line in the file.\n This is the second line in the file.\n \n >>> read_file('non_existing_file.txt')\n File not found\n \"\"\"\n pass",
"execution_count": 10,
"outputs": []
},
{
"metadata": {},
"id": "309828ab",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.315669Z",
"end_time": "2023-04-19T11:33:51.330083Z"
},
"trusted": true
},
"id": "d6e44af8",
"cell_type": "code",
"source": "def read_file(file_name):\n try:\n with open(file_name) as f:\n for line in f:\n print(line.strip())\n except FileNotFoundError:\n print('File not found')",
"execution_count": 11,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.331075Z",
"end_time": "2023-04-19T11:33:51.345293Z"
},
"trusted": true
},
"id": "631c3024",
"cell_type": "code",
"source": "read_file('existing_file.txt')",
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"text": "This is the first line in the file.\nThis is the second line in the file.\n",
"name": "stdout"
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.346293Z",
"end_time": "2023-04-19T11:33:51.360455Z"
},
"trusted": true
},
"id": "d68e60fc",
"cell_type": "code",
"source": "read_file('non_existing_file.txt')",
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"text": "File not found\n",
"name": "stdout"
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.361448Z",
"end_time": "2023-04-19T11:33:51.376462Z"
},
"trusted": true
},
"id": "c47ee603",
"cell_type": "code",
"source": "from pathlib import Path",
"execution_count": 14,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.377447Z",
"end_time": "2023-04-19T11:33:51.392553Z"
},
"trusted": true
},
"id": "6c2dfddc",
"cell_type": "code",
"source": "def read_file(file_name):\n my_file = Path(file_name)\n try:\n with my_file.open() as f:\n for line in f:\n print(line.strip())\n except FileNotFoundError:\n print('File not found')",
"execution_count": 15,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.393553Z",
"end_time": "2023-04-19T11:33:51.408562Z"
},
"trusted": true
},
"id": "295a1768",
"cell_type": "code",
"source": "read_file('existing_file.txt')",
"execution_count": 16,
"outputs": [
{
"output_type": "stream",
"text": "This is the first line in the file.\nThis is the second line in the file.\n",
"name": "stdout"
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.409556Z",
"end_time": "2023-04-19T11:33:51.424562Z"
},
"trusted": true
},
"id": "d56b76cf",
"cell_type": "code",
"source": "read_file('non_existing_file.txt')",
"execution_count": 17,
"outputs": [
{
"output_type": "stream",
"text": "File not found\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "86bfe67b",
"cell_type": "markdown",
"source": "## Merge two dictionaries"
},
{
"metadata": {},
"id": "80e8cff2",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.425554Z",
"end_time": "2023-04-19T11:33:51.439832Z"
},
"trusted": true
},
"id": "48d23d74",
"cell_type": "code",
"source": "x = {'a': 'value_a', 'b': 'old_value_b'}\ny = {'b': 'new_value_b', 'c': 'value_c'}",
"execution_count": 18,
"outputs": []
},
{
"metadata": {},
"id": "1a4072f8",
"cell_type": "markdown",
"source": "Merge `x` and `y` into a new dictionary `z`, such that `z = {'a': 'value_a', 'b': 'new_value_b', 'c': 'value_c'}`."
},
{
"metadata": {},
"id": "219ce410",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.440833Z",
"end_time": "2023-04-19T11:33:51.455233Z"
},
"trusted": true
},
"id": "de18ed44",
"cell_type": "code",
"source": "z = x.copy()\nz.update(y)\nz",
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 19,
"data": {
"text/plain": "{'a': 'value_a', 'b': 'new_value_b', 'c': 'value_c'}"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.456249Z",
"end_time": "2023-04-19T11:33:51.471225Z"
},
"trusted": true
},
"id": "4b7a5281",
"cell_type": "code",
"source": "z = {**x, **y}\nz",
"execution_count": 20,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 20,
"data": {
"text/plain": "{'a': 'value_a', 'b': 'new_value_b', 'c': 'value_c'}"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.472224Z",
"end_time": "2023-04-19T11:33:51.487232Z"
},
"trusted": true
},
"id": "a280fff6",
"cell_type": "code",
"source": "z = x | y\nz",
"execution_count": 21,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 21,
"data": {
"text/plain": "{'a': 'value_a', 'b': 'new_value_b', 'c': 'value_c'}"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "a96cfdd0",
"cell_type": "markdown",
"source": "## Execute an external program or call a system command"
},
{
"metadata": {},
"id": "388b7b6a",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {},
"id": "2783ad05",
"cell_type": "markdown",
"source": "Execute a shell command (for example `dir` in Windows or `ls` in Linux), and get the output."
},
{
"metadata": {},
"id": "b253d50a",
"cell_type": "markdown",
"source": "Remark: for this precise use case, i.e. to handle files and directories, it is better to use Pathlib. This is just an toy example of how to call an external program or system command."
},
{
"metadata": {},
"id": "d91f4f45",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.488228Z",
"end_time": "2023-04-19T11:33:51.503233Z"
},
"trusted": true
},
"id": "2fa39f77",
"cell_type": "code",
"source": "import subprocess",
"execution_count": 22,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.504227Z",
"end_time": "2023-04-19T11:33:51.519371Z"
},
"trusted": true
},
"id": "2bc747f3",
"cell_type": "code",
"source": "output = subprocess.run(\"dir\", shell=True, capture_output=True).stdout",
"execution_count": 23,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.520361Z",
"end_time": "2023-04-19T11:33:51.534500Z"
},
"trusted": true
},
"cell_type": "code",
"source": "print(output.decode('utf-8', errors='ignore'))",
"execution_count": 24,
"outputs": [
{
"output_type": "stream",
"text": " Volume in drive C is OS\r\n Volume Serial Number is 562B-1B7F\r\n\r\n Directory of c:\\Dropbox\\A\\01_Recherche\\Groupe de lecture\\2023 04 19 Fanfan\r\n\r\n04/19/2023 01:33 PM <DIR> .\r\n04/14/2023 01:14 PM <DIR> ..\r\n04/19/2023 10:50 AM <DIR> .ipynb_checkpoints\r\n04/14/2023 05:29 PM 24,931 a_bit_of_gymnastics_in_python_problems_only.ipynb\r\n04/19/2023 11:29 AM 44,854 a_bit_of_gymnastics_in_python_with_solutions.ipynb\r\n04/14/2023 05:19 PM 8,091 draft.ipynb\r\n04/14/2023 02:28 PM 73 existing_file.txt\r\n04/14/2023 04:16 PM <DIR> my\r\n 4 File(s) 77,949 bytes\r\n 4 Dir(s) 2,747,672,657,920 bytes free\r\n\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "b99c68a0",
"cell_type": "markdown",
"source": "## Create a directory if it does not exist (with its parent directories if needed)"
},
{
"metadata": {},
"id": "269fd227",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {},
"id": "28c51765",
"cell_type": "markdown",
"source": "Inside the current working directory, create the directory `my/nice/directory`, but only if needed: the proposed solution should work even if the directory `my`, `my/nice` or `my/nice/directory` already exists."
},
{
"metadata": {},
"id": "9a98a2f8",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.535488Z",
"end_time": "2023-04-19T11:33:51.549712Z"
},
"trusted": true
},
"id": "7c891e59",
"cell_type": "code",
"source": "from pathlib import Path",
"execution_count": 25,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.550703Z",
"end_time": "2023-04-19T11:33:51.565834Z"
},
"trusted": true
},
"id": "934b910b",
"cell_type": "code",
"source": "Path(\"my/nice/directory\").mkdir(parents=True, exist_ok=True)",
"execution_count": 26,
"outputs": []
},
{
"metadata": {},
"id": "ffdcd801",
"cell_type": "markdown",
"source": "## Access the index in 'for' loops"
},
{
"metadata": {},
"id": "26c93a02",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.567831Z",
"end_time": "2023-04-19T11:33:51.581834Z"
},
"trusted": true
},
"id": "5747dadd",
"cell_type": "code",
"source": "nephews = ['Huey', 'Dewey', 'Louie']",
"execution_count": 27,
"outputs": []
},
{
"metadata": {},
"id": "633b27e2",
"cell_type": "markdown",
"source": "Using the above list, write a code that prints:\n\n 0 Huey\n 1 Dewey\n 2 Louie"
},
{
"metadata": {},
"id": "f746be49",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.582827Z",
"end_time": "2023-04-19T11:33:51.596835Z"
},
"trusted": true
},
"id": "55963901",
"cell_type": "code",
"source": "for i, nephew in enumerate(nephews):\n print(i, nephew)",
"execution_count": 28,
"outputs": [
{
"output_type": "stream",
"text": "0 Huey\n1 Dewey\n2 Louie\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "941a85ea",
"cell_type": "markdown",
"source": "## Flatten a list of lists"
},
{
"metadata": {},
"id": "6c6d4892",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.597826Z",
"end_time": "2023-04-19T11:33:51.612834Z"
},
"trusted": true
},
"id": "6f1b5bea",
"cell_type": "code",
"source": "lst_of_lsts = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]",
"execution_count": 29,
"outputs": []
},
{
"metadata": {},
"id": "98321de7",
"cell_type": "markdown",
"source": "Using the above list of lists, output the flattened list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`."
},
{
"metadata": {},
"id": "5796e9ec",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.613826Z",
"end_time": "2023-04-19T11:33:51.628835Z"
},
"trusted": true
},
"id": "1720d030",
"cell_type": "code",
"source": "[x\n for lst in lst_of_lsts\n for x in lst\n]",
"execution_count": 30,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 30,
"data": {
"text/plain": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.629831Z",
"end_time": "2023-04-19T11:33:51.644838Z"
},
"trusted": true
},
"id": "dfb83b3d",
"cell_type": "code",
"source": "result = []\nfor lst in lst_of_lsts:\n result.extend(lst)\nresult",
"execution_count": 31,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 31,
"data": {
"text/plain": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.645826Z",
"end_time": "2023-04-19T11:33:51.660037Z"
},
"trusted": true
},
"id": "39fe9e72",
"cell_type": "code",
"source": "from itertools import chain",
"execution_count": 32,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.661035Z",
"end_time": "2023-04-19T11:33:51.676034Z"
},
"trusted": true
},
"id": "c2cdfc38",
"cell_type": "code",
"source": "list(chain(*lst_of_lsts))",
"execution_count": 33,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 33,
"data": {
"text/plain": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.677036Z",
"end_time": "2023-04-19T11:33:51.692032Z"
},
"trusted": true
},
"id": "9c12fa1a",
"cell_type": "code",
"source": "list(chain.from_iterable(lst_of_lsts))",
"execution_count": 34,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 34,
"data": {
"text/plain": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.693034Z",
"end_time": "2023-04-19T11:33:51.707181Z"
},
"trusted": true
},
"id": "5dc147bb",
"cell_type": "code",
"source": "from functools import reduce\nfrom operator import iconcat",
"execution_count": 35,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.709186Z",
"end_time": "2023-04-19T11:33:51.723190Z"
},
"trusted": true
},
"id": "5b3a3258",
"cell_type": "code",
"source": "reduce(iconcat, lst_of_lsts, [])",
"execution_count": 36,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 36,
"data": {
"text/plain": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2023-04-14T13:20:42.498869Z",
"start_time": "2023-04-14T13:20:42.481874Z"
}
},
"id": "e224d17a",
"cell_type": "markdown",
"source": "## Slicing"
},
{
"metadata": {},
"id": "3798b291",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.724182Z",
"end_time": "2023-04-19T11:33:51.739318Z"
},
"trusted": true
},
"id": "ff00e73c",
"cell_type": "code",
"source": "lst = [x**2 for x in range(10)]\nlst",
"execution_count": 37,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 37,
"data": {
"text/plain": "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "74db9925",
"cell_type": "markdown",
"source": "Use slicing to produce the following desired results..."
},
{
"metadata": {},
"id": "1548c419",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {},
"id": "7748909a",
"cell_type": "markdown",
"source": "`lst[i]` for `i` even, from `i=4` to `i=8` included:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.740311Z",
"end_time": "2023-04-19T11:33:51.755314Z"
},
"trusted": true
},
"id": "2f0f05c7",
"cell_type": "code",
"source": "lst[4:9:2]",
"execution_count": 38,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 38,
"data": {
"text/plain": "[16, 36, 64]"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2023-04-14T13:24:53.288770Z",
"start_time": "2023-04-14T13:24:53.283770Z"
}
},
"id": "a5c0fbd5",
"cell_type": "markdown",
"source": "`lst[i]` from `i=4` to `i=8` included: "
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.756311Z",
"end_time": "2023-04-19T11:33:51.771319Z"
},
"trusted": true
},
"id": "361178fb",
"cell_type": "code",
"source": "lst[4:9]",
"execution_count": 39,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 39,
"data": {
"text/plain": "[16, 25, 36, 49, 64]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "a760936f",
"cell_type": "markdown",
"source": "`lst[i]` from the beginning to `i=3` included:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.772311Z",
"end_time": "2023-04-19T11:33:51.787312Z"
},
"trusted": true
},
"id": "ac33e2a3",
"cell_type": "code",
"source": "lst[:4]",
"execution_count": 40,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 40,
"data": {
"text/plain": "[0, 1, 4, 9]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "1faeeffb",
"cell_type": "markdown",
"source": "`lst[i]` from `i=4` included to the end:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.788524Z",
"end_time": "2023-04-19T11:33:51.802534Z"
},
"trusted": true
},
"id": "dae97f8f",
"cell_type": "code",
"source": "lst[4:]",
"execution_count": 41,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 41,
"data": {
"text/plain": "[16, 25, 36, 49, 64, 81]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "19545ff3",
"cell_type": "markdown",
"source": "`lst[i]` for any `i`:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.803535Z",
"end_time": "2023-04-19T11:33:51.817735Z"
},
"trusted": true
},
"id": "3443cfe9",
"cell_type": "code",
"source": "lst[:]",
"execution_count": 42,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 42,
"data": {
"text/plain": "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "8ffb5445",
"cell_type": "markdown",
"source": "Last value of `lst`:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.818725Z",
"end_time": "2023-04-19T11:33:51.833807Z"
},
"trusted": true
},
"id": "feae4fc6",
"cell_type": "code",
"source": "lst[-1]",
"execution_count": 43,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 43,
"data": {
"text/plain": "81"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2023-04-14T13:27:12.682960Z",
"start_time": "2023-04-14T13:27:12.677041Z"
}
},
"id": "bb6a6d7c",
"cell_type": "markdown",
"source": "Second-to-last value of `lst`:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.834799Z",
"end_time": "2023-04-19T11:33:51.849890Z"
},
"trusted": true
},
"id": "83af658d",
"cell_type": "code",
"source": "lst[-2]",
"execution_count": 44,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 44,
"data": {
"text/plain": "64"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "b4adda59",
"cell_type": "markdown",
"source": "Three last values of `lst`:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.850878Z",
"end_time": "2023-04-19T11:33:51.865020Z"
},
"trusted": true
},
"id": "9118774e",
"cell_type": "code",
"source": "lst[-3:]",
"execution_count": 45,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 45,
"data": {
"text/plain": "[49, 64, 81]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "0daf1fe3",
"cell_type": "markdown",
"source": "All values of `lst`, except the three last ones:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.866011Z",
"end_time": "2023-04-19T11:33:51.881019Z"
},
"trusted": true
},
"id": "b234e821",
"cell_type": "code",
"source": "lst[:-3]",
"execution_count": 46,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 46,
"data": {
"text/plain": "[0, 1, 4, 9, 16, 25, 36]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "3248c0e1",
"cell_type": "markdown",
"source": "All values of `lst` in reverse order:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.882012Z",
"end_time": "2023-04-19T11:33:51.896019Z"
},
"trusted": true
},
"id": "56302035",
"cell_type": "code",
"source": "lst[::-1]",
"execution_count": 47,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 47,
"data": {
"text/plain": "[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "8e5f716f",
"cell_type": "markdown",
"source": "The last three items of `lst`, in reverse order:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.897012Z",
"end_time": "2023-04-19T11:33:51.911145Z"
},
"trusted": true
},
"id": "cb514309",
"cell_type": "code",
"source": "lst[:-4:-1]",
"execution_count": 48,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 48,
"data": {
"text/plain": "[81, 64, 49]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "f7d24af6",
"cell_type": "markdown",
"source": "Everything except the last three items, in reverse order:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.912147Z",
"end_time": "2023-04-19T11:33:51.927146Z"
},
"trusted": true
},
"id": "5d17240f",
"cell_type": "code",
"source": "lst[-4::-1]",
"execution_count": 49,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 49,
"data": {
"text/plain": "[36, 25, 16, 9, 4, 1, 0]"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "b4410b6c",
"cell_type": "markdown",
"source": "## Find the (first) index of an item in a list"
},
{
"metadata": {},
"id": "f4829840",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.928147Z",
"end_time": "2023-04-19T11:33:51.943151Z"
},
"trusted": true
},
"id": "b58e6ae6",
"cell_type": "code",
"source": "lst = ['a', 'b', 'c']",
"execution_count": 50,
"outputs": []
},
{
"metadata": {},
"id": "01c8944d",
"cell_type": "markdown",
"source": "Implement the following function:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.945156Z",
"end_time": "2023-04-19T11:33:51.958395Z"
},
"trusted": true
},
"id": "f5fa3e70",
"cell_type": "code",
"source": "def find_first_index(l, x):\n \"\"\"Find the first index of an item in a list.\n \n Parameters\n ----------\n l: lst\n The list where to search.\n x: object\n The searched element.\n \n Returns\n -------\n int\n Index of `x` in `l`. If `x` is not found, return `len(l)`.\n \n Examples\n --------\n >>> lst = ['a', 'b', 'c']\n >>> find_first_index(lst, 'c')\n 2\n >>> find_first_index(lst, 'z')\n 3\n \"\"\"\n pass",
"execution_count": 51,
"outputs": []
},
{
"metadata": {},
"id": "c0ad67cc",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.959456Z",
"end_time": "2023-04-19T11:33:51.973619Z"
},
"trusted": true
},
"id": "53fc523e",
"cell_type": "code",
"source": "def find_first_index(l, x):\n try:\n return l.index(x)\n except ValueError:\n return len(l)",
"execution_count": 52,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.974047Z",
"end_time": "2023-04-19T11:33:51.989256Z"
},
"trusted": true
},
"id": "0d62f87a",
"cell_type": "code",
"source": "find_first_index(lst, 'c')",
"execution_count": 53,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 53,
"data": {
"text/plain": "2"
},
"metadata": {}
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:51.990284Z",
"end_time": "2023-04-19T11:33:52.004466Z"
},
"trusted": true
},
"id": "46bdf09b",
"cell_type": "code",
"source": "find_first_index(lst, 'z')",
"execution_count": 54,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 54,
"data": {
"text/plain": "3"
},
"metadata": {}
}
]
},
{
"metadata": {},
"id": "72352e49",
"cell_type": "markdown",
"source": "## Iterate over a dictionary"
},
{
"metadata": {},
"id": "a51f65d4",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.005481Z",
"end_time": "2023-04-19T11:33:52.019799Z"
},
"trusted": true
},
"id": "7b55efbe",
"cell_type": "code",
"source": "d = {'a': 0, 'b': 1, 'c': 2}",
"execution_count": 55,
"outputs": []
},
{
"metadata": {},
"id": "84a04bf2",
"cell_type": "markdown",
"source": "Using the above dictionary, write code that prints the keys:\n\n a\n b\n c"
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2023-04-14T14:28:09.384125Z",
"start_time": "2023-04-14T14:28:09.366127Z"
}
},
"id": "1a5ea89c",
"cell_type": "markdown",
"source": "Idem with the values:\n \n 0\n 1\n 2"
},
{
"metadata": {},
"id": "cc58e550",
"cell_type": "markdown",
"source": "Idem with the pairs (key, value):\n\n a 0\n b 1\n c 2"
},
{
"metadata": {},
"id": "ea2264cb",
"cell_type": "markdown",
"source": "### Solution"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.020717Z",
"end_time": "2023-04-19T11:33:52.035717Z"
},
"trusted": true
},
"id": "f2e9b381",
"cell_type": "code",
"source": "for k in d.keys():\n print(k)",
"execution_count": 56,
"outputs": [
{
"output_type": "stream",
"text": "a\nb\nc\n",
"name": "stdout"
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.036716Z",
"end_time": "2023-04-19T11:33:52.050880Z"
},
"trusted": true
},
"id": "f85dadc8",
"cell_type": "code",
"source": "for v in d.values():\n print(v)",
"execution_count": 57,
"outputs": [
{
"output_type": "stream",
"text": "0\n1\n2\n",
"name": "stdout"
}
]
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.051896Z",
"end_time": "2023-04-19T11:33:52.066021Z"
},
"trusted": true
},
"id": "7555e2be",
"cell_type": "code",
"source": "for k, v in d.items():\n print(k, v)",
"execution_count": 58,
"outputs": [
{
"output_type": "stream",
"text": "a 0\nb 1\nc 2\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "2c5abcfc",
"cell_type": "markdown",
"source": "## Bonus problem: global variables"
},
{
"metadata": {},
"id": "2fe06b98",
"cell_type": "markdown",
"source": "### Problem"
},
{
"metadata": {},
"id": "cb235801",
"cell_type": "markdown",
"source": "One of the most popular questions about Python in Stack Overflow deals with global variables."
},
{
"metadata": {},
"id": "427e0d73",
"cell_type": "markdown",
"source": "It is easy to find quite reasonable examples where a global variable is **read** in a function. This mechanism can be used to store and then access the value of a constant:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.067237Z",
"end_time": "2023-04-19T11:33:52.081963Z"
},
"trusted": true
},
"id": "c4863567",
"cell_type": "code",
"source": "SPEED_OF_LIGHT = 299792458\ndef energy_of_mass(m):\n return m * SPEED_OF_LIGHT**2",
"execution_count": 59,
"outputs": []
},
{
"metadata": {},
"id": "f5cb7e10",
"cell_type": "markdown",
"source": "But if you try to find an example where a function **writes** on a global variable, you might find something like this:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.082965Z",
"end_time": "2023-04-19T11:33:52.097943Z"
},
"trusted": true
},
"id": "ba1a5ac8",
"cell_type": "code",
"source": "climate_warming = 0\n\ndef use_car():\n print('Vroom vroom')\n global climate_warming\n climate_warming += 1\n \ndef use_coal_power_plant():\n print('Chug chug')\n global climate_warming\n climate_warming += 1\n \nuse_car()\nuse_car()\nuse_coal_power_plant()\nprint(f\"{climate_warming=}\")",
"execution_count": 60,
"outputs": [
{
"output_type": "stream",
"text": "Vroom vroom\nVroom vroom\nChug chug\nclimate_warming=3\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "2a4e11f9",
"cell_type": "markdown",
"source": "However, this is not very clean, and it would be better to do as in the following (extended) example:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.098935Z",
"end_time": "2023-04-19T11:33:52.113930Z"
},
"trusted": true
},
"id": "d79d3bb8",
"cell_type": "code",
"source": "class Planet():\n def __init__(self):\n self.climate_warming = 0\n\ndef use_car(planet):\n print('Vroom vroom')\n planet.climate_warming += 1\n \ndef use_coal_power_plant(planet):\n print('Chug chug')\n planet.climate_warming += 1\n\ndef capture_co2(planet):\n print('Swoosh')\n planet.climate_warming -= 1\n\nprint('Earth...')\nearth = Planet()\nuse_car(planet=earth)\nuse_car(planet=earth)\nuse_coal_power_plant(planet=earth)\n\nprint('\\nAlternate Earth...')\nalternate_earth = Planet()\nuse_car(alternate_earth)\nuse_coal_power_plant(alternate_earth)\ncapture_co2(alternate_earth)\n\nprint('\\nResults')\nprint(f\"{earth.climate_warming=}\")\nprint(f\"{alternate_earth.climate_warming=}\")",
"execution_count": 61,
"outputs": [
{
"output_type": "stream",
"text": "Earth...\nVroom vroom\nVroom vroom\nChug chug\n\nAlternate Earth...\nVroom vroom\nChug chug\nSwoosh\n\nResults\nearth.climate_warming=3\nalternate_earth.climate_warming=1\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"id": "27e6c9f4",
"cell_type": "markdown",
"source": "So here is the question: try to find a reasonable example where to use global variables and modify them inside one or several functions."
},
{
"metadata": {},
"id": "f239e26f",
"cell_type": "markdown",
"source": "### Proposed solution"
},
{
"metadata": {},
"id": "fedea631",
"cell_type": "markdown",
"source": "Imagine that I have a (badly programmed) Fibonacci function:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.114930Z",
"end_time": "2023-04-19T11:33:52.129175Z"
},
"trusted": true
},
"id": "27037843",
"cell_type": "code",
"source": "def fibo(n):\n if n in {0, 1}:\n return 1\n return fibo(n - 2) + fibo(n - 1)",
"execution_count": 62,
"outputs": []
},
{
"metadata": {},
"id": "b99c2d81",
"cell_type": "markdown",
"source": "In a \"quick and dirty\" way, I would like to count how many times `fibo` is called. Here is a way to do it:"
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.131166Z",
"end_time": "2023-04-19T11:33:52.144979Z"
},
"trusted": true
},
"id": "67034f6e",
"cell_type": "code",
"source": "def fibo(n):\n global count \n count += 1\n if n in {0, 1}:\n return 1\n return fibo(n - 2) + fibo(n - 1)",
"execution_count": 63,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.145979Z",
"end_time": "2023-04-19T11:33:52.160257Z"
},
"trusted": true
},
"id": "faf50fdf",
"cell_type": "code",
"source": "def fibo_count(n):\n global count\n count = 0\n return fibo(n), count",
"execution_count": 64,
"outputs": []
},
{
"metadata": {
"ExecuteTime": {
"start_time": "2023-04-19T11:33:52.161259Z",
"end_time": "2023-04-19T11:33:52.176118Z"
},
"trusted": true
},
"id": "5ec3ddfb",
"cell_type": "code",
"source": "fibo_count(10)",
"execution_count": 65,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 65,
"data": {
"text/plain": "(89, 177)"
},
"metadata": {}
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3 (ipykernel)",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.9.7",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"toc": {
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": true,
"base_numbering": 1,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": true
},
"gist": {
"id": "a3886e8772c603561fa825651ab2b253",
"data": {
"description": "a_bit_of_gymnastics_in_python_with_solutions.ipynb",
"public": true
}
},
"_draft": {
"nbviewer_url": "https://gist.github.com/francois-durand/a3886e8772c603561fa825651ab2b253"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment