{ "cells": [ { "cell_type": "markdown", "id": "searching-meditation", "metadata": {}, "source": [ "# Class hierarchies, Exceptions and Files (17/3 - 2021)" ] }, { "cell_type": "markdown", "id": "outdoor-consultation", "metadata": {}, "source": [ "## Exercise\n", "\n", "Create a class ``volume`` to represent a volume. The calls should have methods ``get_liter``, ``get_imperial_oz``, ``get_us_oz`` to return the volume in liters, imperial fluid ounces, and US fluid ounces.\n", "\n", "Create a subclass ``container`` of ``volume`` that furthermore has an attribute ``material``." ] }, { "cell_type": "code", "execution_count": 59, "id": "interesting-program", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "v.get_liter()=0.29569999999999996\n", "v.get_us_oz()=9.999999999999998\n", "v.get_imperial_oz()=10.408306934178105\n" ] } ], "source": [ "class Volume:\n", " US_OF_IN_LITER = 0.02957\n", " IMPERIAL_OZ_IN_LITER = 0.02841 \n", " \n", " def __init__(self, *, liter=None, us_oz=None, imperial_oz=None):\n", " self._volume = 0 # liter\n", " if liter != None:\n", " self.set_liter(liter)\n", " if us_oz != None:\n", " self.set_us_oz(us_oz)\n", " if imperial_oz != None:\n", " self.set_imperial_oz(imperial_oz)\n", " \n", " def get_liter(self):\n", " return self._volume \n", " \n", " def get_us_oz(self):\n", " return self._volume / Volume.US_OF_IN_LITER\n", " \n", " def get_imperial_oz(self):\n", " return self._volume / Volume.IMPERIAL_OZ_IN_LITER\n", " \n", " def set_us_oz(self, us_oz):\n", " self._volume = us_oz * Volume.US_OF_IN_LITER\n", "\n", " def set_liter(self, liter):\n", " self._volume = liter\n", " \n", " def set_imperial_oz(self, imperial_oz):\n", " self._volume = imperial_oz * Volume.IMPERIAL_OZ_IN_LITER\n", "\n", "v = Volume(us_oz=10)\n", "#v.set_liter(1)\n", "print(f'{v.get_liter()=}')\n", "print(f'{v.get_us_oz()=}')\n", "print(f'{v.get_imperial_oz()=}')" ] }, { "cell_type": "code", "execution_count": null, "id": "incomplete-kitchen", "metadata": {}, "outputs": [], "source": [ "class Container(Volume):\n", " def __init__(self, *, material='unknown', liter=None, us_oz=None, imperial_oz=None):\n", " super().__init__(liter=liter, us_oz=us_oz, imperial_oz=imperial_oz)\n", " self.material = material\n", " \n", "bottle = Container(material='glass', us_oz=10)\n", "#bottle.set_liter(0.25)\n", "\n", "print(bottle.get_liter())\n", "print(bottle.material)" ] }, { "cell_type": "markdown", "id": "cloudy-cabinet", "metadata": {}, "source": [ "## Exercise\n", "\n", "Create a function ``eval_function(f, values)`` that prints ``f(x)`` for all ``x`` in ``values``. If the function raises an error for a value print \"error\" for this value." ] }, { "cell_type": "code", "execution_count": null, "id": "subject-meeting", "metadata": {}, "outputs": [], "source": [ "def eval_function(f, values):\n", " for x in values:\n", " print(x, '->', f(x))\n", " \n", "def square(x):\n", " return x ** 2\n", "\n", "eval_function(square, [1, 2, 3, 4])" ] }, { "cell_type": "code", "execution_count": null, "id": "destroyed-suspension", "metadata": {}, "outputs": [], "source": [ "eval_function(lambda x: x ** 3, [1, 2, 3, 4])" ] }, { "cell_type": "code", "execution_count": null, "id": "champion-boxing", "metadata": {}, "outputs": [], "source": [ "def eval_function(f, values):\n", " for x in values:\n", " try:\n", " answer = f(x)\n", " except Exception:\n", " answer = 'error'\n", " print(x, '->', answer)\n", "\n", "eval_function(lambda x: 1 / x, [-3, -2, -1, 0, 1, 2, 3])" ] }, { "cell_type": "markdown", "id": "meaningful-consultancy", "metadata": {}, "source": [ "## Exercise\n", "\n", "Create a function ``create pairs(X, Y)`` that given two lists ``X`` and ``Y`` returns the list of pairs ``[(X[0], Y[0]), (X[1], Y[1]), ...]``. If the two lists have different length, raise a \"ValueError\" exception." ] }, { "cell_type": "code", "execution_count": null, "id": "academic-appointment", "metadata": {}, "outputs": [], "source": [ "def create_pairs(X, Y):\n", " L = []\n", " for i in range(len(X)):\n", " L.append((X[i], Y[i]))\n", " return L\n", "\n", "print(create_pairs([1, 2, 3], [4, 5, 6]))" ] }, { "cell_type": "code", "execution_count": 56, "id": "nervous-application", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(1, 4), (2, 5), (3, 6)]\n", "[(1, 7), (2, 8)]\n" ] } ], "source": [ "def create_pairs(X, Y):\n", " return list(zip(X, Y))\n", "\n", "print(create_pairs([1, 2, 3], [4, 5, 6]))\n", "print(create_pairs([1, 2, 3], [7, 8])) # ignores 3" ] }, { "cell_type": "code", "execution_count": null, "id": "north-volume", "metadata": {}, "outputs": [], "source": [ "def create_pairs(X, Y):\n", " if len(X) != len(Y):\n", " print('X and Y have different lengths')\n", " return None # will likely cause some problems elsewhere\n", " \n", " return list(zip(X, Y))\n", "\n", "print(create_pairs([1, 2, 3], [4, 5, 6]))\n", "print(create_pairs([1, 2, 3], [7, 8]))" ] }, { "cell_type": "code", "execution_count": null, "id": "public-display", "metadata": {}, "outputs": [], "source": [ "def create_pairs(X, Y):\n", " if len(X) != len(Y):\n", " #raise Exception('X and Y have different lengths')\n", " raise ValueError('X and Y have different lengths')\n", " \n", " return list(zip(X, Y))\n", "\n", "print(create_pairs([1, 2, 3], [4, 5, 6]))\n", "print(create_pairs([1, 2, 3], [7, 8]))" ] }, { "cell_type": "markdown", "id": "documented-shakespeare", "metadata": {}, "source": [ "## Exercise\n", "\n", "Find all occurences of \"mathematic\" in file [cano.txt](https://sherlock-holm.es/ascii/)." ] }, { "cell_type": "code", "execution_count": 53, "id": "appreciated-focus", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " aggregate he becomes a mathematical certainty. You can, for example,\n", " mathematical faculty. At the age of twenty-one he wrote a treatise\n", " strength of it he won the Mathematical Chair at one of our smaller\n", " to ex-Professor Moriarty of mathematical celebrity.\n", " teeth I have barked my knuckles and the retiring mathematical coach,\n", " mathematical master, was sure upon the point. Therefore, it is not\n", " mathematics that it is said that there was no man in the scientific\n", " the mathematical coach at the establishment, a tall, dark, thin man,\n", " Murdoch, the mathematician. A moment later we confronted him upon the\n" ] } ], "source": [ "file = open('cano.txt')\n", "line = file.readline()\n", "while line != '': \n", " if 'mathematic' in line.lower():\n", " print(line, end='') # lines in file end with '\\n'\n", " line = file.readline()\n", "file.close()" ] }, { "cell_type": "code", "execution_count": 52, "id": "clean-sleeve", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " aggregate he becomes a mathematical certainty. You can, for example,\n", " mathematical faculty. At the age of twenty-one he wrote a treatise\n", " strength of it he won the Mathematical Chair at one of our smaller\n", " to ex-Professor Moriarty of mathematical celebrity.\n", " teeth I have barked my knuckles and the retiring mathematical coach,\n", " mathematical master, was sure upon the point. Therefore, it is not\n", " mathematics that it is said that there was no man in the scientific\n", " the mathematical coach at the establishment, a tall, dark, thin man,\n", " Murdoch, the mathematician. A moment later we confronted him upon the\n" ] } ], "source": [ "file = open('cano.txt')\n", "for line in file:\n", " if 'mathematic' in line.lower():\n", " print(line, end='') # lines in file end with '\\n'\n", "file.close()" ] }, { "cell_type": "code", "execution_count": 51, "id": "ordered-singer", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " aggregate he becomes a mathematical certainty. You can, for example,\n", " mathematical faculty. At the age of twenty-one he wrote a treatise\n", " to ex-Professor Moriarty of mathematical celebrity.\n", " teeth I have barked my knuckles and the retiring mathematical coach,\n", " mathematical master, was sure upon the point. Therefore, it is not\n", " mathematics that it is said that there was no man in the scientific\n", " the mathematical coach at the establishment, a tall, dark, thin man,\n", " Murdoch, the mathematician. A moment later we confronted him upon the\n" ] } ], "source": [ "file = open('cano.txt')\n", "cano = file.readlines() # read all data into list\n", "file.close()\n", "for line in cano:\n", " if 'mathematic' in line:\n", " print(line, end='') # lines in file end with '\\n'" ] }, { "cell_type": "code", "execution_count": 36, "id": "velvet-saskatchewan", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " aggregate he becomes a mathematical certainty. You can, for example,\n", " mathematical faculty. At the age of twenty-one he wrote a treatise\n", " to ex-Professor Moriarty of mathematical celebrity.\n", " teeth I have barked my knuckles and the retiring mathematical coach,\n", " mathematical master, was sure upon the point. Therefore, it is not\n", " mathematics that it is said that there was no man in the scientific\n", " the mathematical coach at the establishment, a tall, dark, thin man,\n", " Murdoch, the mathematician. A moment later we confronted him upon the\n" ] } ], "source": [ "with open('cano.txt') as file: # context manager that ensures files get closed\n", " for line in file:\n", " if 'mathematic' in line: print(line, end='')" ] }, { "cell_type": "code", "execution_count": 54, "id": "differential-madrid", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "could not open file\n" ] } ], "source": [ "try:\n", " with open('canon.txt') as file: # context manager that ensures files get closed\n", " for line in file:\n", " if 'mathematic' in line: print(line, end='')\n", "except FileNotFoundError:\n", " print('could not open file')" ] }, { "cell_type": "code", "execution_count": 57, "id": "curious-stretch", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " aggregate he becomes a mathematical certainty. You can, for example,\n", " mathematical faculty. At the age of twenty-one he wrote a treatise\n", " to ex-Professor Moriarty of mathematical celebrity.\n", " teeth I have barked my knuckles and the retiring mathematical coach,\n", " mathematical master, was sure upon the point. Therefore, it is not\n", " mathematics that it is said that there was no man in the scientific\n", " the mathematical coach at the establishment, a tall, dark, thin man,\n", " Murdoch, the mathematician. A moment later we confronted him upon the\n" ] } ], "source": [ "import os\n", "\n", "filename = 'cano.txt'\n", "if os.path.isfile(filename):\n", " with open(filename) as file: # context manager that ensures files get closed\n", " for line in file:\n", " if 'mathematic' in line: print(line, end='')\n", "else:\n", " print('could not open file')" ] } ], "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.9.1" } }, "nbformat": 4, "nbformat_minor": 5 }