{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Solutions Python review questions for final quiz\n", "\n", "Here are a couple of questions that test some python learning\n", "objectives we've covered during the course. Try these on your own\n", "and I'll post the solutions Tuesday evening." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q1: code smell\n", "\n", "**This is not on the final quiz, but is useful information if plan to use python in the future.**\n", "\n", "The cell below, which is taken from [build_2D_matrix.py](https://github.com/phaustin/eosc213_students/blob/master/python/build_2D_matrix.py#L4) isn't wrong but could be improved. Explain how you could alter it\n", "to make it higher quality and less likely to produce an erroneous\n", "result." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def index_to_row_col(ind, nrows, ncols):\n", " \"\"\"\n", " in a 2D array, returns the row and column value\n", " associated with a 1D index\n", " Bottom left is index is zero (0-th row, 0-th column)\n", " while index one is the 0-th row and 1st column\n", " \"\"\"\n", " if ind > nrows * ncols - 1:\n", " return 0\n", "\n", " row = int(np.floor(ind / ncols))\n", " col = int(ind - row * ncols)\n", " return row, col" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n" ] } ], "source": [ "import this" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q1 Answer\n", "\n", "\n", "\n", "When you execute ```import this``` in a jupyter notebook cell (see above) you get\n", "this pair of lines:\n", "\n", "```\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "```\n", "\n", "For the ```index_to_row_col``` function, this means that you should be catching the\n", "out of bounds error and writing a useful error message. As it is written above, users\n", "would always have to check every call of the ```index_to_row_col``` to make sure\n", "that it wasn't returning 0 instead of the expected (row, col) tuple." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Here's how that might look** (Again, exceptions are not on the test, but you definitely\n", "need to understand them for future python programming tasks)." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "def index_to_row_col(ind, nrows, ncols):\n", " \"\"\"\n", " in a 2D array, returns the row and column value\n", " associated with a 1D index\n", " Bottom left is index is zero (0-th row, 0-th column)\n", " while index one is the 0-th row and 1st column\n", " \"\"\"\n", " if ind > nrows * ncols - 1:\n", " err_msg = (f\"ind={ind} exceeds total number of elements\"\n", " f\"tot_num={nrows*ncols}\")\n", " raise ValueError(err_msg)\n", " row = int(np.floor(ind / ncols))\n", " col = int(ind - row * ncols)\n", " return row, col\n", "\n", "# the following command will throw an ValueError exception\n", "#\n", "#index_to_row_col(2000,5,12)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q2 convert row,col to index\n", "\n", "Write a function row_col_to_index that takes a 2-dimensional array shape, \n", "a row number\n", "and a column number and returns the index of that value\n", "of the array. i.e. write the function such that calling\n", "\n", "```\n", "ind=row_col_to_index(nrows,ncols,rownum,colnum)\n", "```\n", "\n", "followed by\n", "\n", "```\n", "rownum,colnum = index_to_row_col(ind, nrows,ncols)\n", "```\n", "\n", "gives the same rownum and colnum back you started with." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q2 answer" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def row_col_to_index(nrows, ncols, rownum, colnum):\n", " \"\"\"\n", " in a 2D array, returns the 1D index associated\n", " with a particular row and column\n", " Index 0 is row 0, col 0 in the bottom left corner\n", " of the array\n", " \"\"\"\n", " totrows,totcols = the_array.shape\n", " the_index=rownum*totcols + colnum\n", " return the_index\n", "\n", "nrows=12\n", "ncols=5\n", "rownum=3\n", "colnum=4\n", "the_array = np.zeros([nrows,ncols])\n", "ind=row_col_to_index(nrows,ncols,rownum,colnum)\n", "row, col = index_to_row_col(ind,nrows,ncols)\n", "assert((row, col) == (rownum,colnum))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q3 build_2D_array\n", "\n", "In the cell below, import the function \n", "[build_2D_matrix](https://github.com/phaustin/eosc213_students/blob/master/python/build_2D_matrix.py#L60) and use it along with imports of the \n", "[Problem_Def](https://github.com/phaustin/eosc213_students/blob/master/python/build_2D_matrix.py#L41)\n", "and \n", "[Boundary_Def](https://github.com/phaustin/eosc213_students/blob/master/python/build_2D_matrix.py#L27)\n", "classes to construct the 2D matrix defined in Question 3 of the\n", "[8_finite_volume_by_hand_ans](https://phaustin.github.io/eosc213/web_notebooks/8_finite_volume_by_hand_ans.html)\n", "assignment\n", "\n", "### Q3 build_2D_array answer" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 64. 84.33333333 104.66666667 125. 64.\n", " 84.33333333 104.66666667 125. 64. 84.33333333\n", " 104.66666667 125. ]\n" ] } ], "source": [ "from build_2D_matrix import Boundary_Def, Problem_Def, build_2D_matrix\n", "import build_2D_matrix as bd\n", "import numpy as np\n", "\n", "west = Boundary_Def(\"const\", val=64.)\n", "east = Boundary_Def(\"const\", val=125.)\n", "north = Boundary_Def(\"flux\", val=0.)\n", "south = Boundary_Def(\"flux\", val=0.)\n", "bc_dict = {\"west\": west, \"north\": north, \"east\": east, \"south\": south}\n", "n_x = 4\n", "n_y = 3\n", "width_x = 800.\n", "width_y = 600.\n", "poro=0.25\n", "Diff=1.e-10\n", "D_matrix = Diff * np.ones((n_y, n_x))\n", "Qsource = np.zeros((n_y, n_x))\n", "prob = Problem_Def(n_x, n_y, poro, width_x, width_y)\n", "A, b = build_2D_matrix(bc_dict, prob, D_matrix, Qsource)\n", "v = np.linalg.solve(A, b)\n", "print(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q4 Python Classes\n", "\n", "Given the class definition and the instance below,\n", "what will this line print?\n", "\n", "```\n", "print(out.data_array[3,:])\n", "```" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[24 25 26 27 28 29 30 31]\n" ] } ], "source": [ "import numpy as np\n", "class hold_data:\n", " def __init__(self,nrows,ncols):\n", " self.data_array=np.arange(0,nrows*ncols)\n", " self.data_array.shape=[nrows,ncols]\n", " \n", "out=hold_data(6,8)\n", "print(out.data_array[3,:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q5 Pandas indexing\n", "\n", "Given the code in the cell below, what will this line print?\n", "\n", "```\n", "print(test.loc[16,'e'] - test.loc[8,'d'])\n", "```" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
bcdefgh
a
01234567
89101112131415
1617181920212223
2425262728293031
3233343536373839
\n", "
" ], "text/plain": [ " b c d e f g h\n", "a \n", "0 1 2 3 4 5 6 7\n", "8 9 10 11 12 13 14 15\n", "16 17 18 19 20 21 22 23\n", "24 25 26 27 28 29 30 31\n", "32 33 34 35 36 37 38 39" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "test=pd.DataFrame(out.data_array,\n", " columns=['a','b','c','d','e','f','g','h'])\n", "test.set_index('a',inplace=True)\n", "test.head()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n" ] } ], "source": [ "print(test.loc[16,'e'] - test.loc[8,'d'])" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "all", "formats": "ipynb,python//py", "notebook_metadata_filter": "all,-language_info", "text_representation": { "extension": ".py", "format_name": "percent", "format_version": "1.2", "jupytext_version": "1.1.0" } }, "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.7.3" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "165px" }, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }