{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Sample Scripts\n", "\n", "* 用同一個 folder 下的 python_sample_answer.ipynb 默寫" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
" ], "text/plain": [ "" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sphinx version。一定有辦法直接把這個 button 加到 sphinx config 裡,有空再研究\n", "\n", "from IPython.display import HTML\n", "\n", "HTML('''\n", "
''')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## fix_seed as a Context Manager" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5488135039273248\n", "0.7731968705194575\n" ] } ], "source": [ "import numpy as np\n", "\n", "class fix_seed:\n", " def __init__(self, seed=0):\n", " self.seed = seed\n", " \n", " def __enter__(self):\n", " np.random.seed(self.seed)\n", " \n", " def __exit__(self, exc_type=None, exc_value=None, traceback=None):\n", " np.random.seed()\n", " \n", "with fix_seed(seed=0):\n", " print(np.random.uniform())\n", "print(np.random.uniform())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exception\n", "\n", "* Open file in a try block with exception handling" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Errno 2] No such file or directory: 'circles_.py'\n", "Done!\n" ] } ], "source": [ "try:\n", " file = open('circles_.py')\n", "except FileNotFoundError as e:\n", " print(e)\n", "else:\n", " print(file.readline())\n", " file.close()\n", "finally:\n", " print('Done!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## unittest\n", "\n", "* 寫一個 ```circle_area``` 計算圓面積,要檢查輸入半徑是否為非負 ```int``` 或 ```float``` 然後寫 test case 測這些 input:```1, 0, 2.1, -2, 3+5j, True, 'radius'```\n", "* 如果是 script 可以在最下面寫 ```unittest.main()``` 開始跑,但在 Jupyter 不行" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from math import pi\n", "import unittest\n", "\n", "def circle_area(r):\n", " if type(r) not in [float, int]:\n", " raise TypeError('Radius must be int or float.')\n", " if r < 0:\n", " raise ValueError('Radius can not be negative.')\n", " \n", " return pi*(r**2)\n", "\n", "class TestCircleArea(unittest.TestCase):\n", " def test_areas(self):\n", " self.assertAlmostEqual(circle_area(1), pi)\n", " self.assertAlmostEqual(circle_area(0), 0)\n", " self.assertAlmostEqual(circle_area(2.1), pi*(2.1**2))\n", " \n", " def test_values(self):\n", " with self.assertRaises(ValueError):\n", " circle_area(-2)\n", " \n", " def test_types(self):\n", " with self.assertRaises(TypeError):\n", " circle_area(3+5j)\n", " circle_area(True)\n", " circle_area('radius')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OOP\n", "\n", "* ```Person``` and ```SuperHero``` classes with ```reveal_id``` methods" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My name is Corey.\n", "My name is Wade Wilson.\n", "And I'm Deadpool.\n" ] } ], "source": [ "class Person:\n", " def __init__(self, name):\n", " self.name = name\n", " \n", " def reveal_id(self):\n", " print(f\"My name is {self.name}.\")\n", " \n", "class SuperHero(Person):\n", " def __init__(self, name, hero_name):\n", " super().__init__(name)\n", " self.hero_name = hero_name\n", " \n", " def reveal_id(self):\n", " super().reveal_id()\n", " print(f\"And I'm {self.hero_name}.\")\n", " \n", "corey = Person('Corey')\n", "corey.reveal_id()\n", "\n", "wade = SuperHero('Wade Wilson', 'Deadpool')\n", "wade.reveal_id()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generator\n", "\n", "* 印 1000 以內的所有 2 的冪次" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 8, 16, 32, 64, 128, 256, 512]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def pow2():\n", " n = 2\n", " while n < 1000:\n", " yield n\n", " n *= 2\n", "\n", "list(pow2())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Decorator \n", "\n", "### fix_seed (No Argument)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5488135039273248\n", "0.6487172323362883\n" ] } ], "source": [ "# fix_seed:固定 seed = 0 版本。離開函數 seed 會還原成 None\n", "\n", "import numpy as np\n", "import functools\n", "\n", "def fix_seed(fnc):\n", " @functools.wraps(fnc)\n", " def wrapper_fix_seed(*args, **kargs):\n", " np.random.seed(0)\n", " res = fnc(*args, **kargs)\n", " np.random.seed()\n", " return res\n", " return wrapper_fix_seed\n", "\n", "@fix_seed\n", "def print_rand():\n", " print(np.random.uniform())\n", " \n", "print_rand()\n", "print(np.random.uniform())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### fix_seed With Argument" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5434049417909654\n", "0.5834370961600464\n" ] } ], "source": [ "# 接受 argument 版本,但變成一定要指定 seed\n", "\n", "import numpy as np\n", "import functools\n", "\n", "def fix_seed(seed=0):\n", " def decorator_fix_seed(fnc):\n", " @functools.wraps(fnc)\n", " def wrapper_fix_seed(*args, **kargs):\n", " np.random.seed(seed)\n", " res = fnc(*args, **kargs)\n", " np.random.seed()\n", " return res\n", " return wrapper_fix_seed\n", " return decorator_fix_seed\n", "\n", "@fix_seed(seed=100)\n", "def print_rand():\n", " print(np.random.uniform())\n", " \n", "print_rand()\n", "print(np.random.uniform())" ] } ], "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.5" } }, "nbformat": 4, "nbformat_minor": 4 }