{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise solutions: working with modules\n", "\n", "### Exercise 4.1\n", "Write a function that creates an empty file `file_name` in a specified directory `dir_name`. \n", "The function should:\n", "* create the directory if needed (support for recursive directory creation is not needed).\n", "* not overwrite/delete any existing files.\n", "* have a `test_mode` argument that, when set to `True`, cleans-up any newly created file and \n", " deletes the directory `dir_name` if it is empty.\n", "\n", "To help you get started, the function's definition, docstring and some pseudocode are already given below.\n", "What you need to do is to flesh-out the body of the `create_empty_file()` function, by replacing the `...` by actual code that does what is indicated in comments. \n", "If you prefer to write your own function, you can of course also do it.\n", "\n", "There are also some lines of codes at the end of the cell to test your function. These lines are already written for you and no edits needed from your side.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "def create_empty_file(file_name, dir_name, test_mode=False):\n", " \"\"\"Create an empty file named 'file_name' in a directory\n", " named 'dir_name'. If test_mode is True the file is\n", " deleted immediatly after it was created.\n", " \"\"\"\n", " # Create a new directory, if it does not already exist.\n", " if not os.path.isdir(dir_name):\n", " os.mkdir(dir_name)\n", "\n", " # Create a new file, if it does not already exist.\n", " file_path = os.path.join(dir_name, file_name)\n", " if os.path.isfile(file_path):\n", " # If the file already exists we have nothing to do\n", " # and exit the function.\n", " return None\n", " \n", " else:\n", " with open(file_path, mode='w') as f:\n", " print('', file=f) \n", " \n", " \n", " # If in test mode, do some cleanup: delete the file and directory we just created.\n", " # Note that the directory is only deleted if it is empty.\n", " if test_mode:\n", " os.remove(file_path)\n", " if not os.listdir(dir_name):\n", " os.rmdir(dir_name)\n", " \n", "\n", "# THIS IS TO TEST YOUR FUNCTION. THERE IS NO NEED TO EDIT ANYTHING AFTER THIS POINT.\n", "# ********************************************************************************* \n", "# Let's test our function.\n", "# To verify that the \"create_empty_file()\" function works as expected, we run\n", "# it a number of times with test mode on and off, and then look at the content\n", "# of \"dir_name\".\n", "dir_name = 'tmp_dir'\n", "create_empty_file('file_1.txt', dir_name)\n", "create_empty_file('file_2.txt', dir_name)\n", "create_empty_file('file_3.txt', dir_name, test_mode=True)\n", "\n", "# Directory \"dir_name\" should contain 'file_1.txt' and 'file_2.txt', but \n", "# not 'file_3.txt' since the later was created in test mode.\n", "print(\"Content of directory\", dir_name, \":\", os.listdir(dir_name))\n", "\n", "# Cleanup.\n", "for file_name in os.listdir(dir_name):\n", " os.remove(os.path.join(dir_name, file_name))\n", "os.rmdir(dir_name)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "## Exercise 4.2\n", "What doe this line of code do? \n", "`time.sleep(3)`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import time\n", "print(help(time.sleep))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The line of code waits for 3 seconds." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "# Additional Exercises\n", "\n", "## Exercise 4.3\n", "Import the function `is_part_of_set` of the `exercise4_3_module` module, located in the same folder as this notebook.\n", "1. What does `is_part_of_set` do ?\n", "2. Determine the result of `is_part_of_set` for all values of x and y from -2 to +2 in increment of 0.05.\n", "3. How long does this computation takes ?\n", "4. How would you represent the result of your work ?\n", "\n", "> Remember the `help()` function. You can also open the module file as a normal text file to read its code.\n", ">\n", "> The grid you have to test for contains 6400 points. Try with a smaller number of points first." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from exercise4_3_module import is_part_of_set\n", "from time import time\n", "\n", "\n", "# Get the current time, so we can compute elapsed time at the end.\n", "t0 = time()\n", "\n", "# We will keep the results in a list of lists.\n", "# Each sub-list contains a row (i.e, different values of x-coordinates for a given y-coordinate)\n", "result = []\n", "step = 0.05\n", "limit = 2\n", "\n", "\n", "# Iterate through all x- and y-coordiantes in the range -2 : +2 with increments of 0.05.\n", "upper_limit = 2\n", "lower_limit = -2\n", "step = 0.05\n", "\n", "y = lower_limit\n", "while y <= limit:\n", " # Add a new line of x-coordinates for the current y-coordinate.\n", " result.append([]) \n", " \n", " # Loop through all x-coordinates.\n", " x = lower_limit\n", " while x <= limit:\n", " # Applying the function to check whether the current coordinate is part of the set or not.\n", " is_set = is_part_of_set(x, y, nb_iter=10) \n", " result[-1].append(is_set) # Add the result at the end of the current line.\n", " x += step\n", " y += step\n", "\n", "print(\"the computation took\", time() - t0, 'seconds')\n", "\n", "# Now, let's print the result by showing a \"*\" character if the coordinate is part of the set and\n", "# an blanck space if it is not.\n", "for row in result:\n", " for cell in row:\n", " # 'cell' is a boolean telling if the (x, y) coordinate are in the set or not.\n", " # Note that we use the end='' argument so that we can continue printing on the same line.\n", " if cell:\n", " print('*', end='')\n", " else:\n", " print(' ', end='')\n", " \n", " print('') # This just causes the printing to go to the next line (because we are finished with this row)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }